- 版本
Java8
1、字符串集合去重
List<String> distinctElements = list.stream().distinct().collect(Collectors.toList());
2、根据对象属性去重
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor){
Map<Object, Boolean> map = new ConcurrentHashMap<>();
return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
//使用举例
persons.stream().filter(distinctByKey(Person::getName))
网友评论