在Java 8中,你可以使用流(Stream)API来给List中的对象的某个字段赋值。这里是一个简单的例子:
peek 方法:
假设你有一个Person类,其中有一个字段叫做
public class Person {
private String name;
// getters and setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
你可以使用以下代码给所有人的名字添加前缀:
List<Person> people = //... your list of people;
List<Person> updatedPeople = people.stream()
.peek(person -> person.setName("Mr. " + person.getName()))
.collect(Collectors.toList());
在这个例子中,
如果你想要给多个字段赋值,你可以在
List<Person> people = //... your list of people;
List<Person> updatedPeople = people.stream()
.peek(person -> {
person.setName("Mr. " + person.getName());
person.setAge("Age " + person.getAge());
})
.collect(Collectors.toList());
注意,
map 方法:
使用
List<Person> people = //... your list of people;
List<Person> updatedPeople = people.stream()
.map(person -> {
Person updatedPerson = new Person();
updatedPerson.setName("Mr. " + person.getName());
updatedPerson.setAge("Age " + person.getAge());
return updatedPerson;
})
.collect(Collectors.toList());
在这个例子中,我们使用