有时我们需要删除list中重复的对象,可以通过stream filter及相关操作,将其删除
public static void main(String[] args) {
//数据模拟
List<Keywords> list = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Keywords keywords = new Keywords();
keywords.setKeyword("a");
list.add(keywords);
}
Keywords keywords = new Keywords();
keywords.setKeyword("1");
list.add(keywords);
//通过stream list的filter操作,过滤掉list中的重复值
List<Keywords> collect = list.stream().filter(distinctByKey(Keywords::getKeyword)).collect(Collectors.toList());
System.out.println(collect);
}
/**
* 获取list中对象属性的重复值
*/
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}