Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining 2 streams from same object in java

I have a list of objects of class A defined as below:

class A {
    private Set<String> sOne;
    private Set<String> sTwo;
    // Constructor, getters and setters
}

Now I would like to create a stream which contains elements of both sOne and stwo. Is there a way to do it in Java 8?

like image 881
Prashant Avatar asked Jul 10 '19 08:07

Prashant


People also ask

How do I combine two streams in Java?

concat() in Java. Stream. concat() method creates a concatenated stream in which the elements are all the elements of the first stream followed by all the elements of the second stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel.

Can we reuse streams in Java?

No. Java streams, once consumed, can not be reused by default. As Java docs say clearly, “A stream should be operated on (invoking an intermediate or terminal stream operation) only once.

What is Strem in Java?

A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.


3 Answers

You can combine them using:

List<A> aList = ...;

Stream<String> stream = aList.stream()
                             .flatMap(a -> Stream.concat(
                                      a.getsOne().stream(), 
                                      a.getsTwo().stream())
                              );
like image 106
ernest_k Avatar answered Nov 01 '22 23:11

ernest_k


Stream.concat(sOne.stream(), sTwo.stream())

You should just be aware that this drops some characteristics IIRC in some cases.

like image 44
Eugene Avatar answered Nov 01 '22 23:11

Eugene


An alternative to already mentioned Stream::concat is the Stream::of:

Stream.of(sOne.stream(), sTwo.stream())
      .flatMap(Function.identity())
      ...

This requires to flatten the structure unless you wish to work with Stream<Stream<T>> or a stream of any collection Stream<Collection<T>>.

like image 44
Nikolas Charalambidis Avatar answered Nov 01 '22 23:11

Nikolas Charalambidis