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());

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM