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