In this source code example, we show how to use Java 8 Collectors.groupingBy() method with an example.
Java 8 Collectors.groupingBy() Example
Java 8 Collectors.groupingBy() Example:
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class JavaCollectGroupByEx {
public static void main(String[] args) {
var items = List.of("pen", "book", "pen", "coin",
"book", "desk", "book", "pen", "book", "coin");
Map result = items.stream().collect(
Collectors.groupingBy(
Function.identity(), Collectors.counting()
));
for (Map.Entry entry : result.entrySet()) {
var key = entry.getKey();
var value = entry.getValue();
System.out.format("%s: %d%n", key, value);
}
}
}
Output:
desk: 1 book: 4 pen: 3 coin: 2