๐๏ธ HashMap์ ์ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ
HashMap์ Map>์ผ๋ก ์ด๊ธฐํํ๊ณ , ์๋ก์ด ๊ฐ (country, city)์ ์ฝ์ ํ๊ณ ์ถ์ต๋๋ค. ์ฌ๋ฌ ๋ฐฉ๋ฒ์ด ์๊ฒ ์ง๋ง, getOrDefault() ๋ฉ์๋๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ๋จํ๊ฒ ํํํ ์ ์์ต๋๋ค. map.put(country, map.getOrDefault(country, new ArrayList()); map.get(country).add(city); ์ด ์ฝ๋๋ฅผ ๋ ์งง๊ฒ ๊ตฌํํ ์๋ ์์๊น์? ํ ์ค๋ก์. computeIfAbsent()๋ฅผ ์ฌ์ฉํ๋ฉด ๋ฉ๋๋ค. map.computeIfAbsent(country, k -> new ArrayList()).add(city); map์ ์ฌ์ฉํ ๋๋ ํค๊ฐ ์ด๋ฏธ map์ ์๋์ง ์ฌ๋ถ๋ฅผ ํ์ ํ๋ ๊ฒ์ด ๋งค์ฐ ์ค์ํฉ๋๋ค. computeIfAbsent() ๋ฉ์๋๋ฅผ ๋ ์ดํด๋ด ์๋ค. V computeIfAbsent(K key, mappingFunction ํค์ ๋งคํ ๋ฉ์๋, ๋ ๊ฐ์ ์ธ์๊ฐ ํ์ํฉ๋๋ค. ๋ง์ฝ ํค๊ฐ map์ ์กด์ฌํ์ง ์๋๋ค๋ฉด ์ง์ ๋ ํค์ ๋ํ ์๋ก์ด ๊ฐ์ ์์ฑํฉ๋๋ค. ํค๊ฐ ์ด๋ฏธ ์กด์ฌํ๋ ๊ฒฝ์ฐ, ๋ฉ์๋๋ ์๋ฌด๊ฒ๋ ํ์ง ์๊ณ ํค์ ์ฐ๊ด๋ ๊ธฐ์กด ๊ฐ์ ๋ฐํํฉ๋๋ค. ๋ ๋ค๋ฅธ ์ ์ฌํ ๋ฉ์๋๋ putIfAbsent(K key, V value) ์ ๋๋ค. ์ญ์๋ ํค๊ฐ ์กด์ฌํ์ง ์๋ ๊ฒฝ์ฐ์ ์ง์ ๋ ๊ฐ์ map์ ์ฝ์ ํฉ๋๋ค. computeIfAbsent์์ ์ฐจ์ด์ ์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค. - ํค๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ์ด ๊ณ์ฐ๋์ง ์์ต๋๋ค. - ํค๊ฐ ์์ผ๋ฉด ์ ํค-๊ฐ ์์ด ์ฝ์ ๋๊ณ ๋ฉ์๋๋ null์ ๋ฐํํฉ๋๋ค. ๊ทธ๋์, ๋ค์๊ณผ ๊ฐ์ ์ฝ๋๋ฅผ ์ฌ์ฉํ์ง ๋ชปํฉ๋๋ค. map.putIfAbsent(country, new ArrayList()).add(city); ๋ง์ฝ country๊ฐ ์ด๋ฏธ ์กด์ฌํ๋ค๋ฉด, ๋ฉ์๋๋ ์๋ฌด๊ฒ๋ ํ์ง ์๊ณ ํด๋น ๊ฐ์ ๋ฐํํฉ๋๋ค. ๊ทธ๋ฌ๋ country๊ฐ ์กด์ฌํ์ง ์๋๋ค๋ฉด, null์ ๋ฐํํ๋ฏ๋ก NullPointerException์ด ๋ฐ์ํฉ๋๋ค.