Java 8 Streams FlatMap方法示例 [英] Java 8 Streams FlatMap method example
问题描述
我一直在检查即将发布的 Java更新
,即: Java 8或JDK 8
。是的,我很不耐烦,有很多新东西,但是,有一些我不明白的东西,一些简单的代码:
I have been checking the upcoming Java update
, namely: Java 8 or JDK 8
. Yes, I am impatient, there's a lot of new stuff, but, there is something I don't understand, some simple code:
final Stream<Integer>stream = Stream.of(1,2,3,4,5,6,7,8,9,10);
stream.flatMap();
javadocs
public< R>流< R> flatMap(函数<?super T,?extends Stream<?extends R>> mapper)
返回包含结果的流用通过将提供的映射函数应用于每个元素而产生的映射流的内容替换该流的每个元素。每个映射的流在其内容放入此流后关闭。 (如果映射的流为空,则使用空流。)
这是一个中间操作。
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.) This is an intermediate operation.
如果有人创建了一些关于 flatMap
的简单现实例子,我将不胜感激,如何在以前的Java版本 Java [6,7]
中编写代码,以及如何使用 Java 8 $ c编写相同的例程$ c>。
I would appreciate if somebody created some simple real-life examples about flatMap
, how you could code it in previous java versions Java[6,7]
and how you can code the same routines using Java 8
.
推荐答案
flatMap
没用已经持平的 Stream ,例如您已在问题中显示的流<整数>
。
It doesn't make sense to flatMap
a Stream that's already flat, like the Stream<Integer>
you've shown in your question.
但是,如果你有一个 Stream< List< Integer>>
那么它会有意义你可以这样做:
However, if you had a Stream<List<Integer>>
then it would make sense and you could do this:
Stream<List<Integer>> integerListStream = Stream.of(
Arrays.asList(1, 2),
Arrays.asList(3, 4),
Arrays.asList(5)
);
Stream<Integer> integerStream = integerListStream .flatMap(Collection::stream);
integerStream.forEach(System.out::println);
将打印:
1
2
3
4
5
要在Java 8之前执行此操作,您只需要一个循环:
To do this pre-Java 8 you just need a loops:
List<List<Integer>> integerLists = Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4),
Arrays.asList(5)
)
List<Integer> flattened = new ArrayList<>();
for (List<Integer> integerList : integerLists)
{
flattened.addAll(integerList);
}
for (Integer i : flattened)
{
System.out.println(i);
}
这篇关于Java 8 Streams FlatMap方法示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!