What is the usage of stream group in Java?
In Java, the group operation of Stream is used to group elements based on a specified condition. It is a terminal operation that returns a Map object consisting of the grouped results. The group operation takes a Function object as a parameter, which is used to generate keys for grouping based on a property or condition of the elements. It then groups the elements in the Stream according to the generated keys and puts the results into the Map.
Here is an example code for the group operation.
List<String> names = Arrays.asList("John", "Mary", "Jane", "John", "Jane");
// 根据名字的首字母进行分组
Map<Character, List<String>> groupByFirstChar = names.stream()
.collect(Collectors.groupingBy(name -> name.charAt(0)));
System.out.println(groupByFirstChar);
The output is:
{J=[John, Jane, John, Jane], M=[Mary]}
In the example above, we grouped a list of strings by the first letter of their names. The groupingBy method takes a Function object that defines how to generate the group key. Here, we used name.charAt(0) to get the first letter of the name as the key. The groupingBy method returns a Map object consisting of the grouping results, where the keys are the group keys and the values are the corresponding lists of elements.
It is important to note that the values in the Map returned by the group operation are List objects that contain all elements corresponding to the given key. If you want to further process the grouped results, you can use other Stream operations to work with these Lists.