1. 对象多个属性代码实现:
List<IcsCheckReport> resultList = resultListAll.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(IcsCheckReport::getChkId).thenComparing(IcsCheckReport::getFeatureId).thenComparing(IcsCheckReport::getBatchId))), ArrayList::new));
2. 单个对象去重:
List<IcsCheckReport> resultList = resultListAll.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(IcsCheckReport::getChkId)), ArrayList::new));
3. 其他方式,可以新建一个List,遍历list判断对象属性,add到新list中。
List<IcsCheckReport> icsCheckReports = new ArrayList<>();HashMap<String, String> map = new HashMap<>();for (IcsCheckReport r1 : icsCheckReports) {String key = r1.getChkId() + r1.getFeatureId() + r1.getBatchId();if (!map.containsKey(key)) {map.put(key, r1.getFeatureId());icsCheckReports.add(r1);}}
4.使用filter过滤
/*** 去重后对象在集合中顺序跟原集合一样* List对象去重,按照对象的某个字段去重,返回去重后新的对象集合* 使用方法:用Stream接口的 filter()接收为参数* */public <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {Map<Object,Boolean> seen = new ConcurrentHashMap<>();return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;}/**** 调用检查过了*/public void main(){try {resultList = resultListAll.stream().filter(distinctByKey(test -> Stream.of(test.getChkId(),test.getFeatureId(),test.getBatchId()).toArray())).collect(Collectors.toList());} catch (Exception e) {log.error("过滤重复要素ID失败", e);e.printStackTrace();}
}