I have a Set<Person> and I need to filter the content and then populate another set out of the given set.
I am fairly new to streams.
The first solution that I can think of is chaining stream().filter().foreach()
Solution 1:
private Set<Person> mapPerson(final Set<Student> student) {
final Set<Person> person = new HashSet<>();
student.stream()
.filter(student1 -> Objects.nonNull(student.getAge()))
.forEach(student1 -> person.add(Person.builder()
.id(student1.getId())
.status(student1.getStatus()))
.build()));
return person;
}
But I am not sure if this can somehow be done by chaining stream().filter().map() ?
Would appreciate any help and also if it is possible to do it both ways, which is the preferred way?
For that, you don't need to create a set manually and then mutate it. You can obtain a set as a result of the execution of the stream pipeline.
First transform a stream of students
Stream<Student>into a stream of person objectsStream<Person>by applying themap()operation, which expects a function that turns the element of the stream into another object of the desired type. So you need to place the logic for creation of aPersonobject that was used insideforEach()intomap().And then apply
collectpassing as parameterCollectors.toSet().The approach you are using is discouraged by the documentation. Have a look at the quote below (emphasize is mine).
You shouldn't utilize
forEach(as well aspeek) which could operate only by causing side effects in situations when there's an alternative way to achieve the same result.In this case, you can do it with a
collect()(as shown above) or by using a plainforloop.