Is it possible to get filtered and unfiltered lists using only one Java stream?

Viewed 11

For learning purposes, imagine I have a list of User objects and this object has a gender field that accepts only male or female values. I also have a isMale() method based on this field.

I need to split this list into one only with males and the other one just with females. Is this possible using only one stream and, obviously, filter with a predicate or do I have to go back to the good old foreach?

I'm trying to achieve these two lists below, but using only one filtered stream and without foreach command or list method.

final var males = users.stream().filter(User::isMale).toList();
final var females = users.stream().filter(u -> !u.isMale()).toList();
0 Answers
Related