使用Java 8 Streams API列出迭代和设置值

jd2*_*050 4 java java-8 java-stream

我试图了解如何使用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; }
}
Run Code Online (Sandbox Code Playgroud)

我有一个List<User>十个用户中的一个,我想将其转换List<UserWithAge>为十个具有相同名称且年龄不变的用户(例如27岁)中的一个。如何使用Java 8 Streams API(无循环,并且不修改上述类)来做到这一点?

Flo*_*ern 5

您可以使用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
Run Code Online (Sandbox Code Playgroud)