×

Java8优雅去重

96
码匠草舍
2018.07.06 14:17 字数 15

字符串集合去重

List<String> distinctElements = list.stream().distinct().collect(Collectors.toList());

根据对象属性去重

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))
日常开发总结
Web note ad 1