0

I have two stream, one contains object of A, one contains object of B, they are in same length. Now I have a class called C, it contains A and B as its fields.

class C {
    A a;
    B b;
}

How can I merge the two stream into one stream using stream operation?

2 Answers2

0

If you have Guava in your classpath, take a look at the Streams.zip utility:

Stream<C> streamC = Streams.zip(streamA, streamB, C::new);

This assumes C has a constructor that accepts A and B:

public C(A a, B b) {
    this.a = a;
    this.b = b;
}
fps
  • 33,623
  • 8
  • 55
  • 110
0

Try this:

public class ZipTest{

    static A[] arrayA;
    static B[] arrayB;
    public static void main(String[] args) {

        //more convenient to zip arrays. if you start with streams
        //collect to arrays : arrayA = streamA.toArray();

        arrayA = new A[] {new A("a1"), new A("a2"), new A("a3")};
        arrayB = new B[] {new B("b1"), new B("b2"), new B("b3")};

        Stream<Object> zippedA_B = IntStream.range(0, 2* Math.min(arrayA.length, arrayB.length))
        .mapToObj( i ->  getElement(i) );

        System.out.println(Arrays.toString(zippedA_B.toArray()));
    }

    private static Object getElement(int i) {

        return ((i%2) == 0) ? arrayA[i/2] : arrayB[i/2];
    }
}

class A{
    String name;
    A(String name){ this.name = name;}
    @Override
    public String toString() {return name;}
}

class B{
    String name;
    B(String name){ this.name = name;}
    @Override
    public String toString() {return name;}
}

Output:

[a1, b1, a2, b2, a3, b3]

c0der
  • 18,467
  • 6
  • 33
  • 65