Java8-使用stream实现list中对象属性的合并

Java8-使用stream实现list中对象属性的合并,不同的属性执行统一(可按照自己的需求对不同的属性执行添加删除等操作)

public static void main(String[] args) {
        List<User> UserList = new ArrayList<>();
        User User = new User();
        User.setId(1);
        User.setAppName("张三");
        User.setAppKey("Android");
        UserList.add(User);

        User User1 = new User();
        User1.setId(2);
        User1.setAppName("张三");
        User1.setAppKey("IOS");
        UserList.add(User1);

        User User2 = new User();
        User2.setId(3);
        User2.setAppName("李四");
        User2.setAppKey("Android");
        UserList.add(User2);

        User User3 = new User();
        User3.setId(4);
        User3.setAppName("李四");
        User3.setAppKey("IOS");
        UserList.add(User3);
        System.out.println("未筛选前:------------------------------");

        UserList.forEach(mp -> {
            System.out.println("name:" + mp.getAppName() + "\tid:" + mp.getId() + "\tchannel:" + mp.getAppKey());
        });


        // 表示appname为key, 接着如果有重复的,那么从User对象mp1与mp2中筛选出一个,这里选择mp1,
        // 并把appname重复,需要将appKey与mp1进行合并的mp2, 赋值给mp1,最后返回赋值给mp1
        List<User> collectList = UserList.stream().collect(Collectors.toMap(User::getAppName, a -> a, (mp1, mp2) -> {
            mp1.setAppKey(mp1.getAppKey() + "," + mp2.getAppKey());
            return mp1;
        })).values().stream().collect(Collectors.toList());
        System.out.println("筛选后:------------------------------");
        collectList.forEach(mp -> {
            System.out.println("name:" + mp.getAppName() + "\tid:" + mp.getId() + "\tchannel:" + mp.getAppKey());
        });
    }

你可能感兴趣的:(java8,stream,java,arraylist,stream)