Java Grouping List: groupingBy() Guide

To group a List according to a certain rule, you can utilize the Collectors.groupingBy() method in Java Stream API. This method can group the elements in the List based on the specified rule, returning a Map object where the keys represent the grouping criteria and the values are the lists of elements belonging to that group.

Here is a simple example: suppose we have a list containing a group of integers, and we want to divide them based on their parity.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

        Map<String, List<Integer>> groupedNumbers = numbers.stream()
                .collect(Collectors.groupingBy(number -> number % 2 == 0 ? "Even" : "Odd"));

        System.out.println(groupedNumbers);
    }
}

In the example above, we used the collect() method and groupingBy() method from Stream API to group elements based on their parity, and store the results in a Map object. The output is as follows:

{Even=[2, 4, 6, 8], Odd=[1, 3, 5, 7, 9]}

Depending on specific needs, Lists can be grouped by different rules and further processed as needed.

bannerAds