What is the usage of groupby in Java?

In Java, the Stream API allows for grouping data. The Collectors.groupingBy() method can be used to achieve functionality similar to the GROUP BY in SQL. By using the groupingBy() method, data can be grouped according to specified conditions, and then operations or aggregations can be applied to each group.

The specific usage is as follows:

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<String> fruits = Arrays.asList("apple", "banana", "grape", "apple", "orange", "banana");

        // 将水果按照首字母进行分组
        Map<Character, List<String>> groupByFirstLetter = fruits.stream()
                .collect(Collectors.groupingBy(s -> s.charAt(0)));

        System.out.println(groupByFirstLetter);
    }
}

In the example above, we grouped the fruits by their first letters to create a Map object, with keys representing the first letter of the fruits and values representing lists of fruits starting with that letter. After running the code, the following result will be printed:

{a=[apple, apple], b=[banana, banana], g=[grape], o=[orange]}

This achieves the functionality of grouping fruits by their first letter. The groupingBy() method can also be combined with methods like Collectors.counting() and Collectors.summingInt() for further operations to achieve more complex grouping and statistical functions.

bannerAds