打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
使用 Java8的 stream对list数据去重,使用filter()过滤列表,list转map

list去重,根据对象某个属性、某几个属性去重

去除List中重复的String

List unique = list.stream().distinct().collect(Collectors.toList());

去除List中重复的对象

// Person 对象public class Person {    private String id;        private String name;        private String sex;    <!--省略 get set-->}
// 根据name去重List<Person> unique = persons.stream().collect(            Collectors.collectingAndThen(                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new));
// 根据name,sex两个属性去重List<Person> unique = persons.stream().collect(           Collectors. collectingAndThen(                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))), ArrayList::new));

filter()过滤列表

List<Person> filterList = persons.stream().filter(p -> p.getSex().equals(1)).collect(Collectors.toList());
List转Map

从一个Person对象的List集合,取出idname组成一个map集合

Map<String, String> collect = list.stream().collect(Collectors.toMap(p -> p.getId(), p -> p.getName()));
从 List 中取出某个属性的组成 list 集合
//1.提取出list对象中的一个属性List<String> stIdList1 = stuList.stream().map(Person::getId).collect(Collectors.toList());//2.提取出list对象中的一个属性并去重List<String> stIdList2 = stuList.stream().map(Person::getId).distinct().collect(Collectors.toList());
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
JDK8都10岁了,你还在用for循环遍历list吗?
Java基础之Java8中map和flatMap的使用
Java stream 排序
collection.stream()以及collect()方法
Java常用的stream流操作,附源码
Java8 Stream:2万字20个实例,玩转集合的筛选、归约、分组、聚合
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服