java8拉姆达表达式对Object去重复
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return object -> seen.putIfAbsent(keyExtractor.apply(object),
Boolean.TRUE) == null;
}
public static void main(String[] args) {
List<EarlyChange> list = new ArrayList<EarlyChange>();
EarlyChange eChange = new EarlyChange("电流",1);
EarlyChange eChange1 = new EarlyChange("烟雾",8);
EarlyChange eChange2 = new EarlyChange("温度",5);
EarlyChange eChange3 = new EarlyChange("电气火灾",7);
EarlyChange eChange4 = new EarlyChange("电气火灾",8);
list.add(eChange);
list.add(eChange1);
list.add(eChange2);
list.add(eChange3);
list.add(eChange4);
//java8拉姆达表达式对Object去重复
List<EarlyChange> collect = list.stream().filter(
distinctByKey(EarlyChange::getName )).collect(Collectors.toList());
for (EarlyChange earlyChange : collect) {
System.out.println(earlyChange);
}
}
结果:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/01c71a154b3f5c43430f016aa50e9316.png)