Creating a Frequency Map
suggest changeThe groupingBy(classifier, downstream) collector collects Stream elements into a Map by classifying each element into a group and performing a downstream operation on the elements in that group.
A classic example of this principle is to use a Map to count the occurrences of elements in a Stream. In this example, the classifier is simply the identity function, which returns the element as-is. The downstream operation counts the number of equal elements, using counting().
Stream.of("apple", "orange", "banana", "apple")
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.forEach(System.out::println);
The downstream operation is itself a collector (Collectors.counting()) that operates on elements of type String and produces a result of type Long. The result of the collect method call is a Map<String, Long>.
This produces one line per entry. groupingBy uses a HashMap, so the order is not guaranteed:
apple=2 orange=1 banana=1