์ผ | ์ | ํ | ์ | ๋ชฉ | ๊ธ | ํ |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- tcp ์ธ๊ทธ๋จผํธ
- ํ ํฐ ๋ฒ์ค
- ์๋น์ค ํ๋ฆฌ๋ฏธํฐ๋ธ
- ํ๋ก์ด๋์์
- reducible
- i-type
- ์ค๋ฅ์ ์ด
- IEEE 802
- git merge
- ๊ฐ๋ฐ์์ทจ์
- ํฐ์คํ ๋ฆฌ์ฑ๋ฆฐ์ง
- well known ํฌํธ
- ๊ทธ๋ฆฌ๋ ์๊ณ ๋ฆฌ์ฆ
- mariadb
- 99ํด๋ฝ
- ์ฝ๋ฉํ ์คํธ์ค๋น
- tcp ํ๋กํ ์ฝ
- ํ๋ ์ ๊ตฌ์กฐ
- leetcode
- xv6
- ์ฃผ๊ธฐ์ ํธ
- ์์๋ฒํธ
- ์ค๋ฅ๊ฒ์ถ
- ์ค๋ ๋
- ๋น์ฃผ๊ธฐ์ ํธ
- ๋ฐ์ดํฐ ์ ์ก
- ํญํด99
- ์ฐ๋ถํฌdb
- ์ค๋ธ์
- til
Archives
- Today
- Total
Unfazedโ๏ธ๐ฏ
interface Map<K,V> - merge ๋ฉ์๋ (๋์ ๋ฐ ํ์ฉ) ๋ณธ๋ฌธ
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 ์ฒ๋ฆฌ๊ฐ ์๋์ผ๋ก ์ด๋ฃจ์ด์ง
- ์กฐ๊ฑด๋ฌธ ์์ด ๊ฐ๊ฒฐํ ์ฝ๋ ์์ฑ ๊ฐ๋ฅ
- ๋งต ์์ ์์ ์ ์์์ ์ผ๋ก ์ฒ๋ฆฌ
์ถ์ฒ :
728x90