Java stream().map()将对象转换为其他对象


1: 將對象List轉為List<String>

public class user{
    private String name;
    private String password;
    private String address;
    private String age;
 }
List<String> name= user.stream().map(x -> x.getName()).collect(Collectors.toList());

2: 將List<String> 轉為對象list
 List<User> result = staff.stream().map(name-> { User user= new User(); user.setName(name); user.setPassword(null); user.setAddress(null); user.setAge(null); return user; }).collect(Collectors.toList());

 

3:將一個對象轉為另一個對象

public class UserInfo { private String name; private String pwd; }

// 需指定對應字段

List<UserInfo> collect = user.stream()

.map(l -> new UserInfo(l.getName(), l.getPassword())).collect(Collectors.toList());

文章參考:https://blog.csdn.net/sanchan/article/details/70753645

               https://www.cnblogs.com/gfbzs/p/13689933.html




免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM