使用Java Lambda Stream语法实现按对象属性去除List当中的重复对象
2022年1月29日
默认提供的stream().distinct()方式去除集合当中的重复对象是通过对象的hasCode方式来判断重复的。如果需要根据某个属性来判断是否重复,则需要通过filter方式自定义一个判断机制,代码如下:
1 2 3 4 |
private <T> Predicate<T> distinctByKey(Function<? super T,?> keyExtractor){ Map<Object,Boolean> map = new ConcurrentHashMap<>(); return t -> map.putIfAbsent(keyExtractor.apply(t),Boolean.FALSE) == null; } |
调用时的代码如下:
1 2 |
List<CourseSchedule> cities = schedules.stream().filter(distinctByKey(CourseSchedule::getCity)).collect(Collectors.toList()); |