flatmap can return a collection in lambda, and then flatten individual elements into the final result set one by one. For example, if there are multiple Hobby(List<Hobby>) in Person, then I want to get all the hobby of everyone, then I can: List<Person> persons = ... Set<Hobby> hobbySet = persons.parallelStream( ).flatMap(p -> p.getHobbyList.stream()) .collect(Collectors.toCollection(() -> new TreeSet<Hobby>( (h1,h2) -> h1.getName(). compareTo(h2.getName()) )))
map: Use the given conversion function to perform conversion operations on the elements contained in the Stream. The newly generated Stream only contains the elements generated by the conversion. This method has three variant methods for primitive types: mapToInt, mapToLong and mapToDouble. These three methods are also relatively easy to understand. For example, mapToInt converts the original Stream into a new Stream. The elements in this newly generated Stream are all int types. The reason why there are three variant methods is to avoid the additional consumption of automatic boxing/unboxing;
map method diagram:
flatMap: similar to map, except that each element is converted into a Stream object, and the elements in the child Stream will be compressed into the parent collection;
flatmap can return a collection in lambda, and then flatten individual elements into the final result set one by one.
For example, if there are multiple Hobby(List<Hobby>) in Person, then I want to get all the hobby of everyone, then I can:
List<Person> persons = ...
Set<Hobby> hobbySet = persons.parallelStream( ).flatMap(p -> p.getHobbyList.stream())
.collect(Collectors.toCollection(() -> new TreeSet<Hobby>(
(h1,h2) -> h1.getName(). compareTo(h2.getName())
)))
For example, a List<?>, map can directly operate each object in the list
Using flatmap enables us to operate deeper levels of data, as follows:
List<List<?>>
map: Use the given conversion function to perform conversion operations on the elements contained in the Stream. The newly generated Stream only contains the elements generated by the conversion. This method has three variant methods for primitive types: mapToInt, mapToLong and mapToDouble. These three methods are also relatively easy to understand. For example, mapToInt converts the original Stream into a new Stream. The elements in this newly generated Stream are all int types. The reason why there are three variant methods is to avoid the additional consumption of automatic boxing/unboxing;
map method diagram:
flatMap: similar to map, except that each element is converted into a Stream object, and the elements in the child Stream will be compressed into the parent collection;
flatMap method diagram: