Java8中map()和flatmap()的用法

map(), flatmap()

二维数组转一维

map()

正常使用的时候无法做到转化维度

比如

1
2
3
4
5
String[] words = new String[]{"Hello","World"};
List<String[]> a = Arrays.stream(words)
.map(word -> word.split(""))
.collect(toList());
a.forEach(System.out::print);

输出结果为两个array的地址

flatmap()

而如果使用flatmap()就可以将其转成同一维度

1
2
3
4
5
6
String[] words = new String[]{"Hello","World"};
List<String> a = Arrays.stream(words)
.map(word -> word.split(""))
.flatMap(Arrays::stream)
.collect(toList());
a.forEach(System.out::print);

二维数组转一维数组

如果是二维数组的情况

1
{ {'a','b'}, {'c','d'}, {'e','f'} };

还是使用flatmap()

1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
String[][] myStringMatrix = new String[][]{{"a", "b"}, {"c", "d"}, {"e", "f"}};
//Stream<String[]>
Stream<String[]> stringStream = Arrays.stream(myStringMatrix);
//Stream<String>
Stream<String> flat = stringStream.flatMap(Arrays::stream);
List<String> list = flat.collect(Collectors.toList(flat));
flat.forEach(System.out::println);
}

这样接下来就可以对合并后的数组集合进行操作

1
{'a','b','c','d','e','f'}
Author: klenq
Link: https://klenq.github.io/2021/12/02/Stream_map()和flatmap()/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.