java8 list 去重

list 按照元素的某个字段去重

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student  {
    private Integer age;
    private String name;
}

测试数据

List<Student> studentList = Lists.newArrayList();
studentList.add(new Student(28, "river"));
studentList.add(new Student(12, "lucy"));
studentList.add(new Student(33, "frank"));
studentList.add(new Student(33, "lucy"));

java8 通过tree set 去重

List<Student> studentDistinctList = studentList.stream()
                .collect(Collectors.collectingAndThen
                        (Collectors.toCollection(() ->
                                        new TreeSet<>(Comparator.comparing(t -> t.getName()))),
                                ArrayList::new
                        )
                );
System.out.println(new Gson().toJson(studentDistinctList));

扩展distinct 方法去重

List<Student> studentDistinct2List = studentList.stream().filter(StreamUtil.distinctByKey(t->t.getName()))
                .collect(Collectors.toList());
System.out.println(new Gson().toJson(studentDistinct2List));

工具类

public class StreamUtil {
    /**
     * https://stackoverflow.com/questions/23699371/java-8-distinct-by-property
     * @param keyExtractor
     * @param <T>
     * @return
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }
}

参考地址
https://stackoverflow.com/questions/23699371/java-8-distinct-by-property

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。