Prashant
Prashant

Reputation: 5403

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?

Upvotes: 6

Views: 427

Answers (3)

Nikolas
Nikolas

Reputation: 44496

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>>.

Upvotes: 1

ernest_k
ernest_k

Reputation: 45339

You can combine them using:

List<A> aList = ...;

Stream<String> stream = aList.stream()
                             .flatMap(a -> Stream.concat(
                                      a.getsOne().stream(), 
                                      a.getsTwo().stream())
                              );

Upvotes: 5

Eugene
Eugene

Reputation: 121028

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

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

Upvotes: 5

Related Questions