Posts

Showing posts from August, 2019

Java Collectors recipes

Java Collectors is a utility class with several reduction operations. Here a few of the example you can do with the Collectors class. For example, grouping functionality first. import java.util.stream.Collectors; import java.util.stream.Stream; // basic functionality of the collector Stream.of("one", "two", "three", "four", "five") .collect(Collectors.groupingBy(n -> n.length())); // = {3=[one, two], 4=[four, five], 5=[three]} In the above code, n -> n.length() is the classifier . The return type is Map<Integer, List<String>> in the line# 5 - 6. The grouping allows having a downstream collector which do the subsequent collection operation. For example, // basic functionality of the collector Stream.of("one", "two", "three", "four", "five") .collect(Collectors.groupingBy(n -> n.length() , Collectors.counting())); // = {3=2, 4=