- 前言
- 一、非对象列表去重
- 1.使用方法
- 二、对象列表去重
- 1.通过stream的filter()方法
- 2.stream流的衍生功能
- 2.1.单个字段或条件
- 2.2.多个字段或条件
- 三、anyMatch()列表里是否包含某个元素
- 四、allMatch()列表里元素都是某个值
- 五、noneMatch()列表里元素都不是某个值
- 总结
前言
以下是日常开发中用到的比较多的一些方法,整理在一起方便查阅
一、非对象列表去重 1.使用方法
ListchangeList = list.stream().distinct().collect(Collectors.toList()); //list原列表
注意:distinct()是基于hashcode()和equals()工作的,故不支持对对象的列表进行去重
二、对象列表去重 1.通过stream的filter()方法public staticPredicate distinctByKey(Function super T, ?> keyExtractor) { Map
List2.stream流的衍生功能 2.1.单个字段或条件lists = list.stream().filter(distinctByKey(b->b.getXXX())).collect(Collectors.toList()); //Entity用到的对象
ArrayList2.2.多个字段或条件collect = list.stream().collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>( Comparator.comparing( Entity::getXXX))), ArrayList::new)); //getXXX进行比较的对象属性
ArrayList三、anyMatch()列表里是否包含某个元素collect1 = entityList.stream().collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>( Comparator.comparing(p->p.getXXXA() + ";" + p.getXXXB()))), ArrayList::new);
List四、allMatch()列表里元素都是某个值list = Arrays.asList(1, 2, 1, 1, 1); boolean flag = list.stream().anyMatch(f -> f == (1)); //返回true boolean flag2 = list.stream().anyMatch(a -> StrUtil.isNotBlank(a) && a.equals("1")); //多条件
List五、noneMatch()列表里元素都不是某个值list = Arrays.asList(1, 2, 1, 1, 1); boolean flag = list.stream().allMatch(f -> f == (1)); //返回false boolean flag2 = list.stream().allMatch(a -> StrUtil.isNotBlank(a) && a.equals("1")); //多条件
List总结list = Arrays.asList(1, 2, 1, 1, 1); boolean flag = list.stream().noneMatch(f -> f == (1)); //返回false boolean flag2 = list.stream().noneMatch(a -> StrUtil.isNotBlank(a) && a.equals("1")); //多条件
以上就是一些常用的方法汇总。



