在Java中,使用Stream的groupBy方法可以对Stream中的元素进行分组操作
在Java中,使用Stream的groupBy方法可以对Stream中的元素进行分组操作。groupBy方法接受一个Function作为参数,该函数用于提取元素的键值,并返回一个Map对象,其中键是分组的值,值是属于该分组的元素列表。
示例如下:
假设有一个包含Person对象的List,每个Person对象有一个age属性,我们想按照age属性进行分组:
List<Person>persons=Arrays.asList(
newPerson("Alice",25),
newPerson("Bob",30),
newPerson("Charlie",25),
newPerson("David",30)
);
Map<Integer,List<Person>>groupedByAge=persons.stream()
.collect(Collectors.groupingBy(Person::getAge));
groupedByAge.forEach((age,people)->{
System.out.println("Age"+age+":"+people);
});
在这个例子中,我们首先使用stream方法将List转换为Stream,然后使用collect方法和groupingBy方法进行分组操作。最后,我们通过forEach方法遍历每个分组,并输出结果。
注意:在上面的例子中,Person类需要实现一个getAge方法来获取年龄属性。
版权声明
本文仅代表作者观点,不代表博信信息网立场。