java8 flatmap
天蓬老师
天蓬老师 2017-04-18 09:59:19
0
3
408

java8 stream 的 flatmap 跟map有啥区别?有例子不

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
伊谢尔伦

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())
)))

PHPzhong

For example, a List<?>, map can directly operate each object in the list

List<Integer> integers = new ArrayList<>();
//添加数据略
integers.stream.map(i -> i + 1).foreach(System.out::println);

Using flatmap enables us to operate deeper levels of data, as follows:
List<List<?>>


List<List<Integer>> outer = new ArrayList<>();
List<Integer> inner1 = new ArrayList<>();
inner1.add(1);
List<Integer> inner2 = new ArrayList<>();
inner1.add(2);
List<Integer> inner3 = new ArrayList<>();
inner1.add(3);
List<Integer> inner4 = new ArrayList<>();
inner1.add(4);
List<Integer> inner5 = new ArrayList<>();
inner1.add(5);
outer.add(inner1);
outer.add(inner2);
outer.add(inner3);
outer.add(inner4);
outer.add(inner5);
List<Integer> result = outer.stream().flatMap(inner -> inner.stream().map(i -> i + 1)).collect(toList());
System.out.println(result);
左手右手慢动作

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:

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template