map与flatmap的区别
时间: 2023-08-03 21:04:05 浏览: 40
在Java中,`map`和`flatMap`是两个常用的函数式接口,它们的作用是对集合进行转换和处理。
`map`函数接受一个函数作为参数,该函数将集合中的每个元素映射到另一个元素。它返回一个新的集合,其中包含了原始集合中的每个元素经过映射后得到的新元素。例如,将一个字符串列表中的每个字符串转换为大写字母可以使用`map`函数:
```java
List<String> strings = Arrays.asList("hello", "world");
List<String> upperCaseStrings = strings.stream()
.map(str -> str.toUpperCase())
.collect(Collectors.toList());
```
`flatMap`函数也接受一个函数作为参数,但该函数返回一个流。`flatMap`函数将每个元素映射到一个流,并将这些流合并成一个流。例如,将一个字符串列表中的每个字符串拆分为单词后,再将所有单词放入一个列表中可以使用`flatMap`函数:
```java
List<String> strings = Arrays.asList("hello world", "goodbye world");
List<String> words = strings.stream()
.flatMap(str -> Arrays.stream(str.split(" ")))
.collect(Collectors.toList());
```
总的来说,`map`是进行一对一的映射转换,而`flatMap`是进行一对多的映射转换。