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


 

 

1: 將對象List轉為List

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

2: 將List 轉為對象list
 List 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 collect = user.stream()

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