• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

Java8 stream 根据对象字段去重

java 来源:isyoungboy 3次浏览
public class Java8StreamTest {

    public static class Book{

        private String id;

        private String name;

        public Book(String id, String name) {
            this.id = id;
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Book{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                '}';
        }
    }

    @Test
    public void testUnique(){
        List<Book> books = Lists.newArrayList(new Book("1","1"),new Book("2","2"),new Book("3","3"),new Book("2","2"));

		//使用TreeSet去重
        List<Book> unique1 = books.stream().collect(
                collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getId()))),
                        ArrayList::new));

        System.out.println(unique1);

		//使用map去重
        List<Book> unique2 = books.stream()
                .filter(distinctByKey(o -> o.getId()))
                .collect(Collectors.toList());
        System.out.println(unique2);

    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        System.out.println("这个函数将应用到每一个item");
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

}

版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)