Reputation: 5403
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
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
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
Reputation: 121028
Stream.concat(sOne.stream(), sTwo.stream())
You should just be aware that this drops some characteristics IIRC in some cases.
Upvotes: 5