gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:02:22 25 4
gpt4 key购买 nike

我正在尝试了解如何使用 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>十个用户,我想将其转换为 List<UserWithAge>十个具有相同名字和固定年龄(比如 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

关于java - 使用 Java 8 Streams API 列出迭代和设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42683590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com