studentList = studentList.stream().distinct().collect(Collectors.toList()); out.print("distinct去重后:"); out.println(objectMapper.writeValueAsString(studentList)); // 这里我们将 distinctByKey() 方法作为 filter() 的参数,过滤掉那些不能加入到 set 的元素 studentList = studentList.stream().fil...
list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()->newTreeSet<>(Comparator.comparing(s -> s.getAge())), ArrayList::new)) .forEach(System.out::println); }//次方法来源于:https://blog.csdn.net/haiyoung/article/details/80934467static<T> Predicate<T> distinctByKey1...
System.out.println("指定age属性去重(方法三):"); list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(s -> s.getAge())), ArrayList::new)) .forEach(System.out::println); } static <T> Predicate<T> distinctByKey1(Function<?
内部是用reduce实现的啊,想到reduce,瞬间想到一种自己实现distinctBykey的方法。我只要用reduce,计算部分就是把Stream的元素拿出来和我自己内置的一个HashMap比较,有则跳过,没有则放进去。其实,思路还是最开始的那个最直白的方法。 @Test public void dis3() { users.parallelStream().filter(distinctByKey(User::g...
Java stream根据对象某个字段过滤重复数据:distinctByKey 一、原生的distinct()不支持按照列表里的对象某个属性去重 二、对某个字段过滤重复数据:使用HashMap privatestatic<T> Predicate<T> distinctByKey(Function<?superT, ?>keyExtractor) { Map<Object, Boolean> seen =newConcurrentHashMap<>();returnt -> ...
使用Java的Stream去重 回到最初的问题,之所以提这个问题是因为想要将数据库侧去重拿到Java端,那么数据量可能比较大,比如10w条。对于大数据,采用Stream相关函数是最简单的了。正好Stream也提供了distinct函数。那么应该怎么用呢? users.parallelStream().distinct().forEach(System.out::println); ...
distinct() 方法声明如下: Streamdistinct(); 1.1 对于 String 列表的去重 因为String 类已经覆写了 equals() 和 hashCode() 方法,所以可以去重成功。 @Test public void listDistinctByStreamDistinct() { // 1. 对于 String 列表去重 ListstringList = new ArrayList() {{ ...
List<Entity>lists=list.stream().filter(distinctByKey(b->b.getTid())).collect(Collectors.toList()); Java集合List去重的几种方式 : 1、使用LinkedHashSet删除arraylist中的重复数据 2、使用java8新特性stream进行List去重 3、利用HashSet不能添加重复数据的特性 由于HashSet不能保证添加顺序,所以只能作为判断...
⼆、对某个字段过滤重复数据:使⽤HashMap private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) { Map<Object, Boolean> seen = new ConcurrentHashMap<>();return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;} list.stream().filter(...
stream().filter(distinctByKey(Student::getName)).collect(Collectors.toList()); out.print("根据名字去重后 :"); out.println(objectMapper.writeValueAsString(studentList)); } 结果如下 去重前 :[{"stuNo":"001","name":"Tom"},{"stuNo":"001","name":"Tom"},{"stuNo":"003","name":"...