๊ด€๋ฆฌ ๋ฉ”๋‰ด

Unfazedโ—๏ธ๐ŸŽฏ

interface Map<K,V> - merge ๋ฉ”์„œ๋“œ (๋™์ž‘ ๋ฐ ํ™œ์šฉ) ๋ณธ๋ฌธ

Java

interface Map<K,V> - merge ๋ฉ”์„œ๋“œ (๋™์ž‘ ๋ฐ ํ™œ์šฉ)

9taetae9 2024. 12. 12. 17:34
728x90

1. ๋ฉ”์„œ๋“œ ์‹œ๊ทธ๋‹ˆ์ฒ˜ ๋ถ„์„

public V merge(
        K key,                    // ๋งต์—์„œ ์‚ฌ์šฉํ•  ํ‚ค
        V value,                  // ์ƒˆ๋กœ์šด ๊ฐ’ (null์ด ์•„๋‹ˆ์–ด์•ผ ํ•จ)
        BiFunction<? super V,     // ๋‘ ๊ฐœ์˜ ๊ฐ’์„ ๋ฐ›์•„์„œ
                ? super V,     // ํ•˜๋‚˜์˜ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜
                ? extends V> remappingFunction
)

2. ๋™์ž‘ ์‹œ๋‚˜๋ฆฌ์˜ค

A. ํ‚ค๊ฐ€ ์—†๊ฑฐ๋‚˜ ๊ฐ’์ด null์ธ ๊ฒฝ์šฐ

Map<String, Integer> map = new HashMap<>();
// ํ‚ค "A"๊ฐ€ ์—†์„ ๋•Œ
map.merge("A", 1, Integer::sum); // ๊ทธ๋ƒฅ {"A"=1} ์ €์žฅ

 

B. ํ‚ค๊ฐ€ ์ด๋ฏธ ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ:

Map<String, Integer> map = new HashMap<>();
map.put("A",5);
// ํ‚ค "A"๊ฐ€ ์ด๋ฏธ ์žˆ์„ ๋•Œ
map.merge("A",1,Integer::sum); // {"A"=6}
// remappingFunction(5, 1)์ด ์‹คํ–‰๋˜์–ด 6์ด ์ €์žฅ๋จ

 

C. remappingFunction์ด null์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒฝ์šฐ:

Map<String, Integer> map = new HashMap<>();
map.put("A", 5);
map.merge("A", 1, (old, new) -> null); // "A" ํ‚ค๊ฐ€ ์ œ๊ฑฐ๋จ

 

3. ์ฃผ์˜์‚ฌํ•ญ

Map<String, Integer> map = new HashMap<>();

// ์ž˜๋ชป๋œ ์‚ฌ์šฉ: remappingFunction ๋‚ด์—์„œ map ์ˆ˜์ •
map.merge("A", 1, (old, new) -> {
    map.put("B", 2);  // ConcurrentModificationException ๋ฐœ์ƒ ๊ฐ€๋Šฅ
    return old + new;
});

// ์˜ฌ๋ฐ”๋ฅธ ์‚ฌ์šฉ
map.merge("A", 1, (old, new) -> old + new);

 

 

4. ํ™œ์šฉ ์˜ˆ์‹œ

// 1. ๋ฌธ์ž์—ด ์—ฐ๊ฒฐ
Map<String, String> stringMap = new HashMap<>();
stringMap.merge("greeting", "Hello", (old, new) -> old + " " + new);

// 2. ์นด์šดํ„ฐ ์ฆ๊ฐ€
Map<String, Integer> countMap = new HashMap<>();
countMap.merge("count", 1, Integer::sum);

// 3. ์ตœ๋Œ€๊ฐ’ ์œ ์ง€
Map<String, Integer> maxMap = new HashMap<>();
maxMap.merge("max", 10, Integer::max);

// 4. ๋ฆฌ์ŠคํŠธ ํ•ฉ์น˜๊ธฐ
Map<String, List<String>> listMap = new HashMap<>();
listMap.merge("items",
        Arrays.asList("item1"),
        (oldList, newList) -> {
        List<String> merged = new ArrayList<>(oldList);
        merged.addAll(newList);
        return merged;
    }
);

 

5. ๋‚ด๋ถ€ ๋™์ž‘ ์˜์‚ฌ์ฝ”๋“œ(Pseudo-code)

V oldValue = map.get(key);
V newValue;

if (oldValue == null) {
    newValue = value;
} else {
    newValue = remappingFunction.apply(oldValue, value);
    if (newValue == null) {
        map.remove(key);
        return null;
    }
}
map.put(key, newValue);
return newValue;

 

 

merge ๋ฉ”์„œ๋“œ ์ฃผ์š” ์žฅ์ 

 

  • Thread-safeํ•œ ๋ฐฉ์‹์œผ๋กœ "ํ™•์ธ ํ›„ ์ˆ˜์ •" ์ž‘์—…์„ ์ˆ˜ํ–‰
  • null ์ฒ˜๋ฆฌ๊ฐ€ ์ž๋™์œผ๋กœ ์ด๋ฃจ์–ด์ง
  • ์กฐ๊ฑด๋ฌธ ์—†์ด ๊ฐ„๊ฒฐํ•œ ์ฝ”๋“œ ์ž‘์„ฑ ๊ฐ€๋Šฅ
  • ๋งต ์ˆ˜์ • ์ž‘์—…์„ ์›์ž์ ์œผ๋กœ ์ฒ˜๋ฆฌ

 

 

 

 

์ถœ์ฒ˜ :

https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/HashMap.html#merge(K,V,java.util.function.BiFunction)

728x90