本文主要是介绍拉姆达表达式实现对集合中的对象中的某个属性求和以及查询某个特定属性以及对特定属性求和以及针对集合根据某个属性以key-value形式分组,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
废话不多说 直接上代码 求和
List<UserEntity> userEntities = new ArrayList<UserEntity>();userEntities.add(new UserEntity(20L, "张三",1,1L));userEntities.add(new UserEntity(20L, "张三",1,1L));userEntities.add(new UserEntity(22L, "李四",2,2L));userEntities.add(new UserEntity(10L, "王五",3,3L));// Map<String, List<UserEntity>> user = userEntities.stream().collect
// (Collectors.groupingBy(UserEntity::getAge));Long collect1 = userEntities.stream().collect(Collectors.summingLong(UserEntity::getAge));Long collect2 = userEntities.stream().collect(Collectors.summingLong(UserEntity::getSex));Long collect3 = userEntities.stream().collect(Collectors.summingLong(UserEntity::getUserId));System.out.println(collect1+"000");System.out.println(collect2+"+++");System.out.println(collect3+"---");
运行结果
7000
7+++
72---
代码 查询特定属性
List<UserEntity> userEntities = new ArrayList<UserEntity>();userEntities.add(new UserEntity(20L, "张三",1,1L));userEntities.add(new UserEntity(20L, "张三",1,1L));userEntities.add(new UserEntity(22L, "李四",2,2L));userEntities.add(new UserEntity(10L, "王五",3,3L));// Map<String, List<UserEntity>> user = userEntities.stream().collect
// (Collectors.groupingBy(UserEntity::getAge));List<Long> collect1 = userEntities.stream().map(UserEntity::getAge).collect(Collectors.toList());List<Long> collect2 = userEntities.stream().map(UserEntity::getUserId).collect(Collectors.toList());List<Integer> collect3 = userEntities.stream().map(UserEntity::getSex).collect(Collectors.toList());System.out.println(collect1+" ===");System.out.println(collect2+" ---");System.out.println(collect3+" 000");double sum = userEntities.stream().mapToDouble(UserEntity::getUserId).sum();System.out.println(sum+" sum");
运行结果
[1, 1, 2, 3] ===
[20, 20, 22, 10] ---
[1, 1, 2, 3] 000
72.0 sum
代码 分组
List<UserEntity> userEntities = new ArrayList<UserEntity>();userEntities.add(new UserEntity(20L, "张三",1,1L));userEntities.add(new UserEntity(20L, "张三",1,1L));userEntities.add(new UserEntity(22L, "李四",2,2L));userEntities.add(new UserEntity(10L, "王五",3,3L));// Map<String, List<UserEntity>> user = userEntities.stream().collect
// (Collectors.groupingBy(UserEntity::getAge));Map<Long, List<UserEntity>> collect = userEntities.stream().collect(Collectors.groupingBy(UserEntity::getAge));System.out.println(collect+" collect");
结果
{1=[UserEntity{userId=20, username='张三', sex=1, age=1}, UserEntity{userId=20, username='张三', sex=1, age=1}],
2=[UserEntity{userId=22, username='李四', sex=2, age=2}],
3=[UserEntity{userId=10, username='王五', sex=3, age=3}]} collect
参考博客
获取集合的某个属性
这辈子坚持与不坚持都不可怕,怕的是独自走在坚持的道路上!! 欢迎加入技术群聊。。
这篇关于拉姆达表达式实现对集合中的对象中的某个属性求和以及查询某个特定属性以及对特定属性求和以及针对集合根据某个属性以key-value形式分组的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!