温馨提示×

java中stream groupby怎么使用

小亿
226
2024-02-21 12:23:24
栏目: 编程语言

在Java中,使用Stream的groupBy方法可以对Stream中的元素进行分组操作。groupBy方法接受一个Function作为参数,该函数用于提取元素的键值,并返回一个Map对象,其中键是分组的值,值是属于该分组的元素列表。

示例如下:

假设有一个包含Person对象的List,每个Person对象有一个age属性,我们想按照age属性进行分组:

List<Person> persons = Arrays.asList(
    new Person("Alice", 25),
    new Person("Bob", 30),
    new Person("Charlie", 25),
    new Person("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方法来获取年龄属性。

0