Java中的flatMap主要用于处理嵌套的集合结构,将多个集合或流合并为一个集合或流。它适合以下场景:
List<List<String>> nestedList = Arrays.asList(
Arrays.asList("a", "b"),
Arrays.asList("c", "d"),
Arrays.asList("e", "f")
);
List<String> flattenedList = nestedList.stream()
.flatMap(list -> list.stream())
.collect(Collectors.toList());
Stream<String> stream1 = Stream.of("a", "b", "c");
Stream<String> stream2 = Stream.of("d", "e", "f");
Stream<String> combinedStream = Stream.concat(stream1, stream2)
.flatMap(s -> Stream.of(s.split("")));
Optional<List<String>> optionalList = Optional.of(Arrays.asList("a", "b"));
Optional<String> optionalValue = optionalList.flatMap(list -> list.stream()
.reduce((a, b) -> a + b));
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<Integer> lengths = names.stream()
.flatMap(name -> Stream.of(name.length()))
.filter(length -> length % 2 == 0)
.collect(Collectors.toList());
总之,flatMap在处理嵌套集合、合并流、处理Optional类型以及执行过滤和映射组合等场景中非常有用。