stream流中根据id去重

    public static void main(String[] args) {
        List<User> userList = new ArrayList<>();
        userList.add(new User("1","李大锤","23","南京"));
        userList.add(new User("2","张无忌","18","西安"));
        userList.add(new User("3","刘德华","26","苏州"));
        userList.add(new User("4","郭靖","33","上海"));

        userList.add(new User("1","李大锤","23","南京"));
        userList.add(new User("3","带头大哥","36","杭州"));
        System.out.println("原数据"+userList);

        userList =userList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(User::getId))), ArrayList::new));

        System.out.println("现数据"+userList);


    }

效果:

原数据:[User(id=1, username=李大锤, password=23, address=南京), User(id=2, username=张无忌, password=18, address=西安), User(id=3, username=刘德华, password=26, address=苏州), User(id=4, username=郭靖, password=33, address=上海), User(id=1, username=李大锤, password=23, address=南京), User(id=3, username=带头大哥, password=36, address=杭州)]

去重后的数据:[User(id=1, username=李大锤, password=23, address=南京), User(id=2, username=张无忌, password=18, address=西安), User(id=3, username=刘德华, password=26, address=苏州), User(id=4, username=郭靖, password=33, address=上海)]

你可能感兴趣的:(面试题,list)