java8 把一个list的元素放到另外一个list

 public static void main(String[] args){
        list();
    }

    public static void list(){
        List<User> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();

        User user1 = new User();
        user1.setRealName("汪1");
        user1.setPhone("1");
        list1.add(user1);

        User user2 = new User();
        user2.setRealName("汪2");
        user2.setPhone("2");
        list1.add(user2);

        User user3 = new User();
        user3.setRealName("汪3");
        user3.setPhone("3");
        list1.add(user3);

        User user4 = new User();
        user4.setRealName("汪4");
        user4.setPhone("4");
        list1.add(user4);

        list1.stream().forEach(user -> {
            logger.info("list1元素遍历:"+user.getRealName());
        });

        //把user的realName全部拉出来存放到list2中
        list2 = list1.stream().map(user->{return user.getRealName();}).collect(Collectors.toList());
        logger.info(list2.toString());
        list2.stream().forEach(ss -> {
            logger.info("list2遍历:"+ss);
        });

    }

结果如下:

14:14:29.440 [main] INFO  - list1元素遍历:汪1
14:14:29.443 [main] INFO  - list1元素遍历:汪2
14:14:29.443 [main] INFO  - list1元素遍历:汪3
14:14:29.443 [main] INFO  - list1元素遍历:汪4
14:14:29.447 [main] INFO  - [汪1, 汪2, 汪3, 汪4]
14:14:29.448 [main] INFO  - list2遍历:汪1
14:14:29.448 [main] INFO  - list2遍历:汪2
14:14:29.448 [main] INFO  - list2遍历:汪3
14:14:29.448 [main] INFO  - list2遍历:汪4
    原文作者:IT云清
    原文地址: https://blog.csdn.net/weixin_39800144/article/details/80018086
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞