jdk1.8常用总结

1.查找集合里的第一个对象---filter

例:查找List<T> list 中userName为小明的对象T

list.stream().filter(...).findFirst()

1) list.stream().filter(e ->"小明".equals(e.getUserName())

).findFirst();

 

2.查找满足条件的对象,并返回集合---filter、collect

2) list.stream().filter(...).collect(Collectors.toList())

list.stream()

 .filter(e ->

 "小明"equals(e.getUserName())

).collect(Collectors.toList());

 

3.获取对象集合中所有的userName集合 ---map

List<String> nameList = list.stream().map(T: :getUserName).collect(Collectors.toList()); //方法1

List<String> nameList =list.stream().map(e ->e.getUserName()).collect(Collectors.toList()); //方法2

 

3.List 转map

Map<String,String> map =list.stream().collect(Collectors.toMap(Student::getId,Student: :getName));

如果id有重复 则指定唯一的id,如下:

Map<String,String> map =list.stream().collect(Collectors.toMap(Student : :getId,Student : :getName, (key1,key2) -> key1));

 

4.对指定的list对象里的某一个字段排序

list.stream().sorted(Comparator.comparing(Person : :getNameId).thenComparing(Person : :getAge)).collect(Collectors.toList());

或者Collections.sort(list, Comparator.comparing(User : :getAge));  

//降序   Collections.sort(list, Comparator.comparing(User : :getAge).reverse());  

//5.去重

list.stream()

 .collect(

             Collectors.collecingAndThen(

                             Collectors.toCollection( () -> new TreeSet<>(Comparator.comparing(User : :getId))),

                             ArrayList : :new

                              ));

//两个字段去重

list.stream()

 .collect(

             Collectors.collecingAndThen(

                             Collectors.toCollection( () -> new TreeSet<>(Comparator.comparing(user ->user.getId +user.getAge)))),

                             ArrayList : :new

                              ));

6.分组 按照id分组,一组多个的情况,取每组第一个

list.stream().collect(Collectors.groupingBy(User::getId,Collectors.collectors.collectingAndThen(Collectors.toList(),v -> v.get(0))));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值