pojo类中list存储其他字段_List集合流处理类型小结

本文为博主原创,未经允许不得转载

对应实体类

importlombok.Getter;importlombok.Setter;

@Getter

@Setterpublic classStudent {privateString name;private intage;privateString className;privateString birthday;

}

1.根据字段取出某一个字段属性的集合

List studentList = new ArrayList<>();

List newList =studentList.stream().map(Student::getAge).collect(Collectors.toList());for(Student student : newList) {

System.out.println(student.getName()+"---"+student.getAge());

}

2。List根据某个字段升序排序

List studentList = new ArrayList<>();

List newList =studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());for(Student student : newList) {

System.out.println(student.getName()+"---"+student.getAge());

}

3.List根据某个字段排序降序

List list = new ArrayList<>();

list= list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());

4.获取某一字段属性值对应的数据集合

List resultList =studentList.stream()

.filter((Student stu)->area.equals(stu.getAge()))

.collect(Collectors.toList());

5.根据某个字段值获取出对应的对象

Student stu =studentList.stream()

.filter(p-> "2018-08-12 12:10".equals(p.getBirthday()))

.findAny().orElse(null);

6.对集合元素去重

List nameList = new ArrayList<>();

nameList= nameList.stream().distinct().collect(Collectors.toList());

7.对集合某一个属性进行求和

List stuList = new ArrayList<>();double totalAge = stuList.stream().collect(Collectors.summingDouble(Student::getAge));

8。获取集合中的某一个属性的数据集合并去重

// 所有的ip信息对象集合

List netInfoList =netIpService.queryNetIpList();

// 从所有IP信息对象集合中根据机房id过滤出所有机房id不同的数据对象,并根据机房id去重

List distinctIpRoomList =netInfoList.stream().collect(Collectors

.collectingAndThen(Collectors.toCollection(()-> new TreeSet<>(

Comparator.comparing(NetiIpInfo::getIpRoomId))), ArrayList::new));

代码是很简答,很优雅的

解释一下

list.stream(): 是把list集合转化为stream集合

sorted(): 进行排序,其中Comparator.comparing(Student::getAge)表示按照年纪排序,

.reversed()表示是逆序,因为默认情况下,不加.reversed 是升序的

collect(Collectors.toList()): 再次将排序后的stream集合转化为list集合

.findAny()表示将其中任意一个返回;

.orElse(null)表示如果一个都没找到返回null

distinct() 对集合元素或对象去重

summingDouble() 对集合元素进行求和为double类型数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值