一、根据对象中属性去重

/**
     * java8 list<java bean>去重
     */
    @Test
    public void listRemoveDuplication() {
        List<User> users = new ArrayList<>();
        users.add(new User(1L, "aa", "aa"));
        users.add(new User(1L, "aa", "bb"));
        users.add(new User(1L, "aa", "cc"));
        users = users.stream().collect(
                collectingAndThen(
                        toCollection(
                                () -> new TreeSet<>(Comparator.comparing(User::getId))), ArrayList::new
                )
        );

        for (User user : users) {
            System.out.println(user);
        }

    }

java 对象里面的属性多个参数 java根据多个属性去重_Test

二、根据对象中多个属性去重

/**
     * java8 list<java bean> 根据多个bean属性去重
     * 根据属性id和pwd去重,满足id和pwd都一致时,视为相同属性
     */
    @Test
    public void listRemoveDuplication2() {
        List<User> users = new ArrayList<>();
        users.add(new User(1L, "aa", "aa"));
        users.add(new User(1L, "aa", "bb"));
        users.add(new User(1L, "aa", "cc"));
        users = users.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(
                                () -> new TreeSet<>(
                                        Comparator.comparing(
                                                o -> o.getId()
                                                        + ";"
                                                        + o.getPwd()
                                        )
                                )
                        ), ArrayList::new
                )
        );

        for (User user : users) {
            System.out.println(user);
        }

    }

java 对象里面的属性多个参数 java根据多个属性去重_java_02

三、java8 去除重复字符串

/**
     * java8 list<String> 去除重复的string
     */
    @Test
    public void stringRemoveDuplication() {
        List<String> strings = new ArrayList<>();
        strings.add("aa");
        strings.add("aa");
        strings.add("bb");
        strings.add("cc");
        strings = strings.stream().distinct().collect(Collectors.toList());

        for (String str : strings) {
            System.out.println(str);
        }
    }

java 对象里面的属性多个参数 java根据多个属性去重_java_03