Reputation: 175
I have a class as
public class Student{
private String name;
private String school;
}
and a list of Student
objects
List<Student> students = new ArrayList();
suppose I have already populated the name
field of each Student
object.
Now I want to populate the school field of each object with the same value, say "XYZ school". How can I do this using Java 8 stream()?
I tried in following way but it gives error.
List<Student> xyzStudent = students.stream()
.map(o -> o.setSchool("XYZ school"));
Should I use map
there or something else? And how can I collect the the result in xyzStudent
?
Upvotes: 1
Views: 4946
Reputation: 15086
First of all, there is nothing wrong with good old for each loop, even in java 8:
for (Student s : students) {
s.setSchool("XYZ school");
}
You can use foreach terminal operation to achieve the same behaviour.
students.stream().forEach(s -> s.setSchool("XYZ school"));
Although some people say that operation done in forEach on a stream should not have side effects.
Upvotes: 2