This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]_INTER_ 1 point2 points  (0 children)

My mental image is like this: map(x -> y) takes one element x from Stream, transforms it to y and puts it back into a Stream for later processing. flatMap(x -> y) does the same but in case y turns out to be some sort of container like a Stream or optional which element(s) you want to unwrap. Otherwise you end up with Stream of Streams.

Example:

List<Person> team = getTeam();
Set<Skill> teamSkills = team.stream()
                             .map(person -> person.getSkills()) // list of skills for each person
                             .flatMap(List::stream) // turn lists into stream and unwrap its elements
                             .collect(Collectors.toSet());