简体   繁体   English

在java 8中合并具有不同类型和长度的多个流

[英]Merging multiple streams in java 8 with different types and length

How can I merge multiple streams in java 8 with different types and length如何在java 8中合并具有不同类型和长度的多个流

Stream<String> x = Stream.of("A", "B", "C");
Stream<Integer> y = Stream.of(3, 7);
Stream<Float> z = Stream.of(1.1f, 2.2f);

Expected result, is a steam that holds something like this:预期的结果是一个包含如下内容的蒸汽:

A 3 1.1f
A 3 2.2f
A 7 1.1f
A 7 2.2f
B 3 1.1f
B 3 2.2f
B 7 1.1f
B 7 2.2f
C 3 1.1f
C 3 2.2f
C 7 1.1f
C 7 2.2f

You'll have to define some class that holds these 3 properties.您必须定义一些包含这 3 个属性的类。 Let's call it Triplet .我们称之为Triplet

But since we have to stream over some of the sources of data multiple times, it's better to start with List s, not Stream s:但是由于我们必须多次流式传输某些数据源,因此最好从List开始,而不是Stream

List<String> x = List.of("A", "B", "C");
List<Integer> y = List.of(3, 7);
List<Float> z = List.of(1.1f, 2.2f);

(If you must start with Stream s, you'll have to collect the second and third Stream s into List s first). (如果必须从Stream开始,则必须首先将第二个和第三个Stream收集到List )。

Now you can write:现在你可以写:

Stream<Triplet> triplets =
    x.stream()
     .flatMap(a -> y.stream()
                    .flatMap (b -> z.stream()
                                    .map(c -> new Triplet(a,b,c))));

If you wish, you can make the Triplet class generic (and then produce a Stream<Triplet<String,Integer,Float>> ).如果您愿意,您可以使Triplet类通用(然后生成Stream<Triplet<String,Integer,Float>> )。

Since the original question used streams as input and those are not reusable, I want to add my version which converts the second and third streams to lists (with the performance penalty of list creation).由于最初的问题使用流作为输入并且这些流不可重用,我想添加我的版本,将第二个和第三个流转换为列表(列表创建的性能损失)。 If performance is an issue it would be best if you could have at least two of the streams as lists in the first place.如果性能是一个问题,那么最好首先将至少两个流作为列表。

Also, if you want to use the org.apache.commons:commons-lang3:3.9 library you have the Triple class which can hold the result.此外,如果您想使用org.apache.commons:commons-lang3:3.9库,您可以使用 Triple 类来保存结果。

    List<Integer> yList = y.collect(Collectors.toList());
    List<Float> zList = z.collect(Collectors.toList());
    Stream<Triple<String, Integer, Float>> newStream =
            x.flatMap(a -> yList.stream()
                    .flatMap (b -> zList.stream()
                            .map(c -> Triple.of(a, b, c))));
    newStream.forEach(System.out::println);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM