๐ฏ ์์ดํ 45. ์คํธ๋ฆผ์ ์ฃผ์ํด์ ์ฌ์ฉํ๋ผ.
์คํธ๋ฆผ API๋ ๋ค์ฌ๋ค๋ฅํ์ฌ ์ฌ์ค์ ์ด๋ ํ ๊ณ์ฐ์ด๋ผ๋ ํด๋ผ ์ ์๋ค. ํ์ง๋ง ํ ์ ์๋ค๋ ๋ป์ด์ง, ํด์ผ ํ๋ค๋ ๋ป์ ์๋๋ค!!
์คํธ๋ฆผ์ ์ ๋๋ก ์ฌ์ฉํ๋ฉด ํ๋ก๊ทธ๋จ์ด ์งง๊ณ ๊น๊ธํด์ง์ง๋ง, ์๋ชป ์ฌ์ฉํ๋ฉด ์ฝ๊ธฐ ์ด๋ ต๊ณ ์ ์ง๋ณด์๋ ํ๋ค์ด์ง๋ค.
์ฌ์ ํ๋๋ฅผ ํ์ด ์์ ์๊ฐ ๋ง์ ์๋๊ทธ๋จ ๊ทธ๋ฃน๋ค์ ์ถ๋ ฅํ๋ค.
public class IterativeAnagrams { public static void main(String[] args) throws IOException { String[] sArr = new String[]{"abc","euq","test","zzfq","que","acb"}; int minGroupSize = Integer.parseInt("1"); Map<String, Set<String>> groups = new HashMap<>(); for (String s : sArr) { String word = s; groups.computeIfAbsent(alphabetize(word), (unused) -> new TreeSet<>()).add(word); } for (Set<String> group : groups.values()) if (group.size() >= minGroupSize) System.out.println(group.size() + ": " + group); } private static String alphabetize(String s) { char[] a = s.toCharArray(); Arrays.sort(a); return new String(a); } }
์คํธ๋ฆผ์ ๊ณผํ๊ฒ ์ฌ์ฉํ๋ค.
public class StreamAnagrams { public static void main(String[] args) throws IOException { int minGroupSize = Integer.parseInt("1"); Stream<String> words = Stream.of("abc","euq","test","zzfq","que","acb"); words.collect( groupingBy(word -> word.chars().sorted() .collect(StringBuilder::new, (sb, c) -> sb.append((char) c), StringBuilder::append).toString())) .values().stream() .filter(group -> group.size() >= minGroupSize) .map(group -> group.size() + ": " + group) .forEach(System.out::println); } }
์คํธ๋ฆผ์ ๊ณผ์ฉํ๋ฉด ํ๋ก๊ทธ๋จ์ด ์ฝ๊ฑฐ๋ ์ ์ง๋ณด์ํ๊ธฐ ์ด๋ ค์์ง๋ค.*
์คํธ๋ฆผ์ ์ ์ ํ ํ์ฉํ๋ฉด ๊น๋ํ๊ณ ๋ช ๋ฃํด์ง๋ค.
public class HybridAnagrams { public static void main(String[] args) throws IOException { Stream<String> words = Stream.of("abc","euq","test","zzfq","que","acb"); int minGroupSize = Integer.parseInt("1"); words.collect(groupingBy(word -> alphabetize(word))) .values().stream() .filter(group -> group.size() >= minGroupSize) .forEach(g -> System.out.println(g.size() + ": " + g)); } private static String alphabetize(String s) { char[] a = s.toCharArray(); Arrays.sort(a); return new String(a); } }
๊ธฐ์กด ์ฝ๋๋ ์คํธ๋ฆผ์ ์ฌ์ฉํ๋๋ก ๋ฆฌํฉํฐ๋งํ๋, ์ ์ฝ๋๊ฐ ๋ ๋์ ๋ณด์ผ ๋๋ง ๋ฐ์ํ์.
์คํธ๋ฆผ์ด ์์ฃผ ์์ฑ๋ง์ถค์ธ ์กฐ๊ฑด
- ์์๋ค์ ์ํ์ค๋ฅผ ์ผ๊ด๋๊ฒ ๋ณํํ๋ค.
- ์์๋ค์ ์ํ์ค๋ฅผ ํํฐ๋งํ๋ค.
- ์์๋ค์ ์ํ์ค๋ฅผ ํ๋์ ์ฐ์ฐ์ ์ฌ์ฉํด ๊ฒฐํฉํ๋ค.
- ์์๋ค์ ์ํ์ค๋ฅผ ์ปฌ๋ ์ ์ ๋ชจ์๋ค.
- ์์๋ค์ ์ํ์ค์์ ํน์ ์กฐ๊ฑด์ ๋ง์กฑํ๋ ์์๋ฅผ ์ฐพ๋๋ค.
์ฐธ๊ณ ์๋ฃ
Joshua Bloch, ใEffective Java 3/Eใ, ๊ฐ์๋งต์ ์ฎ๊น, ํ๋ก๊ทธ๋๋ฐ์ธ์ฌ์ดํธ(2018)
http://www.kyobobook.co.kr/product/detailViewKor.laf?ejkGb=KOR&mallGb=KOR&barcode=9788966262281&orderClick=LEa&Kc=