Java8 stream 根据对象字段去重(简单粗暴)

Java8 stream 根据对象字段去重

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;
    }

}

Java8的stream对list中的对象进行去重

首先我们有一个对象属性如下

@Data
public class Person {
    private String id;
    private String name;
    private String sex;
}

我们根据属性name来去重,去重代码如下

List<Person> persons = new ArrayList();
//赋值初始化过程省略
List<Person> uniqueByName = persons.stream().collect(
            Collectors.collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new)
);

根据name,sex两个属性去重

List<Person> persons = new ArrayList();
//赋值初始化过程省略
List<Person> uniqueByNameAndSex = persons.stream().collect(
           Collectors. collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))), ArrayList::new)
);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值