Collections.sort(words, new Comparator<Strin>() {
public int compare(String s1, String s2) {
return Integer.compare(s1.length(), s2.length());
}
});
를 람다로 변환
Collections.sort(words,
(s1, s2) -> Integer.compare(s1.length(), s2.length()));
map.merge(key, 1, (count, incr) -> count + incr);
람다로 변환
map.merge(key, 1, Integer::sum);
메서드 참조 유형
스트림 API가 제공하는 추상 개념
public class Anagrams {
public static void main(String[] args) throws FileNotFoundException {
File dictionary = new File(args[0]);
int minGroupSize = Integer.parseInt(args[1]);
Map<String, Set<String>> groups = new HashMap<>();
try (Scanner s = new Scanner(dictionary)) {
while (s.hasNext()) {
String word = s.next();
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);
}
}
computeIfAbsent : 맵 안에 키가 있는지 찾고 있으면 단순 매핑값 반환, 키 없으면 건네진
함수 객체를 키에 적용하고 값을 계산 후 그 키와 매핑한 후 값을 반환
위 코드를 스트림을 이용하여 변환
public class AnagramStream {
public static void main(String[] args) throws IOException {
Path dictionary = Paths.get(args[0]);
int minGroupSize = Integer.parseInt(args[1]);
try (Stream<String>words = Files.lines(dictionary)){
words.collect(groupingBy(word -> alphabetize(word)))
.values().stream()
.filter(group -> group.size() >= minGroupSize)
.forEach(g -> System.out.println(g.size() + ": " + g));
}
}
}
위 코드는 중간 연산은 없고, 종단 연산에서 모든 단어를 수집해 맵으로 모은다
스트림을 사용하면 좋은 경우
스트림 패러다임의 핵심 : 계산을 일련의 변환으로 재구성함
→ 각 단계는 이전 단계의 결과를 받아 처리하는 순수함수여야 한다
순수함수 : 오직 입력만이 결과에 영향을 주는 함수
잘못 사용된 스트림
public class wrong {
Map<String, Long> freq = new HashMap<>();
try (Stream<String> words = new Scanner(file).tokens()) {
words.forEach(word -> {
freq.merge(word.toLowerCase(), 1L, Long::sum);
});
}
}
제대로 사용된 스트림
public class Correct {
Map<String, Long> freq;
try (Stream<String> words = new Scanner(file).tokens()) {
freq = words
.collect(groupingBy(String::toLowerCase, counting()));
}
}