jdk8 Stream map和flatMap区别
程序员文章站
2022-06-08 22:18:28
...
-
1.map
- 将一种类型的值转换为另外一种类型的值。
- 代码:将List 转换成List
List<String> collected = Stream.of("a", "b").collect(Collectors.toList());
List<Integer> figure = collected.stream().map(s -> {
Integer i;
switch (s) {
case "a":
i = 1;
break;
case "b":
i = 2;
break;
default:
i = -1;
break;
}
return i;
}).collect(Collectors.toList());
-
2.flatMap(类似C# AddRange)
- 将多个Stream连接成一个Stream,这时候不是用新值取代Stream的值,与map有所区别,这是重新生成一个Stream对象取而代之。
List<Integer> a=new ArrayList<>();
a.add(1);
a.add(2);
List<Integer> b=new ArrayList<>();
b.add(3);
b.add(4);
List<Integer> figures=Stream.of(a,b).flatMap(u->u.stream()).collect(Collectors.toList());
figures.forEach(f->System.out.println(f));
-
或者看下面这个例子
-
flatMap方法
- List<String> words = new ArrayList<String>();
- words.add("your");
- words.add("name");
-
-
- public static Stream<Character> characterStream(String s){
- List<Character> result = new ArrayList<>();
- for (char c : s.toCharArray())
- result.add(c);
- return result.stream();
- }
- Stream<Stream<Character>> result = words.map(w -> characterStream(w));
- Stream<Character> letters = words.flatMap(w -> characterStream(w));
如果使用的是flatMap方法,返回的是['y', 'o', 'u', 'r', 'n', 'a', 'm', 'e']
这是map和flatMap的区别
-
@Test public void testMapAndFlatMap() { List<String> words = new ArrayList<String>(); words.add("hello"); words.add("word"); //将words数组中的元素再按照字符拆分,然后字符去重,最终达到["h", "e", "l", "o", "w", "r", "d"] //如果使用map,是达不到直接转化成List<String>的结果 List<String> stringList = words.stream() .flatMap(word -> Arrays.stream(word.split(""))) .distinct() .collect(Collectors.toList()); stringList.forEach(e -> System.out.println(e)); }