java stream 对象去重

单属性和多属性去重 

 List personList = new ArrayList();
        personList.add(new User("鸣人", "22", "", "1", null,null,"",""));
        personList.add(new User("鸣人", "22", "", "1", null,null,"",""));
        personList.add(new User("小樱", "22", "", "1", null,null,"",""));

        // list 一个条件 去重
        List uniqueByName = personList.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getUsername))), ArrayList::new));
        System.out.println("一个条件去重后的list:" +JSON.toJSONString(uniqueByName));

        // list 多个条件 去重
        List uniqueBySalaryAndAge = personList.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(
                                Comparator.comparing(p -> p.getUsername() + ";" + p.getNickName()))), ArrayList::new));
        

你可能感兴趣的:(java,java,开发语言)