我试图了解如何使用Java 8 Streams API。
例如,我有以下两个类:
public class User {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
public class UserWithAge {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
private int age;
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
我有一个List<User>
10位用户,我想将其转换List<UserWithAge>
为10位具有相同名称且年龄不变的用户(例如27岁)。如何使用Java 8 Streams API(没有循环,并且无需修改上述类)来做到这一点?
您可以使用map()
流的功能将User
列表中的每个实例转换为一个UserWithAge
实例。
List<User> userList = ... // your list
List<UserWithAge> usersWithAgeList = userList.stream()
.map(user -> {
// create UserWithAge instance and copy user name
UserWithAge userWithAge = new UserWithAge();
userWithAge.setName(user.getName());
userWithAge.setAge(27);
return userWithAge;
})
.collect(Collectors.toList()); // return the UserWithAge's as a list
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句