欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > Stream API进行分组并收集某个属性到List

Stream API进行分组并收集某个属性到List

2025/9/18 9:47:48 来源:https://blog.csdn.net/weixin_73060959/article/details/144034278  浏览:    关键词:Stream API进行分组并收集某个属性到List

在Java中,使用Stream API进行分组并收集某个属性到List中是一种常见的操作。这可以通过Collectors.groupingByCollectors.mapping结合使用来实现。下面是一个具体的示例:

假设我们有一个Person类,其中包含nameage属性,我们想要根据age属性对Person对象进行分组,并将每个组中的name属性收集到一个List中。

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;public class Person {private String name;private int age;// 构造函数、getter 和 setter 省略public Person(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public int getAge() {return age;}
}// 某个地方在业务逻辑中使用Stream API进行分组
import java.util.Arrays;public class GroupingExample {public static void main(String[] args) {List<Person> people = Arrays.asList(new Person("zhangsan", 30),new Person("lisi", 30),new Person("wangwu", 25),new Person("zhaoliu", 25),new Person("tianqi", 30));Map<Integer, List<String>> peopleByAge = people.stream().collect(Collectors.groupingBy(Person::getAge, // 分组的键Collectors.mapping(Person::getName, Collectors.toList()) // 将name属性收集到List中));peopleByAge.forEach((age, names) -> {System.out.println("Age: " + age);names.forEach(name -> System.out.println("\t" + name));});}
}

在这个例子中:

  • people.stream():将people列表转换为流。
  • Collectors.groupingBy(Person::getAge):根据Person对象的age属性进行分组。
  • Collectors.mapping(Person::getName, Collectors.toList()):对于每个分组,将Person对象的name属性映射并收集到一个List中。

最终,peopleByAge是一个Map,其键是年龄,值是对应年龄的name列表。使用forEach打印出每个年龄组及其对应的名称列表。

这种方法是处理集合分组和属性收集的非常强大且表达式的方式,充分利用了Java 8及以上版本的Stream API的功能。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词