Grouping and Partitioning

Learn about the `groupingBy` and `partitioningBy` method.

Introduction to grouping and partitioning

The groupingBy collector groups elements based on a function we provide. For example:

List<Dragon> dragons = getDragons();
Map<Character,List<Dragon>> map = dragons.stream()
        .collect(groupingBy(dragon -> dragon.getName().charAt(0)));

Similarly, the partitioningBy method creates a map with a boolean key. For example:

// Group by whether or not the dragon is green
Map<Boolean,List<Dragon>> map = dragons.stream()
         .collect(partitioningBy(Dragon::isGreen));

Get hands-on with 1400+ tech skills courses.