[英]Joining 2 streams from same object in java
I have a list of objects of class A
defined as below: 我有一个
A
类对象列表,定义如下:
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
. 现在我想创建一个包含
sOne
和stwo
元素的流。 Is there a way to do it in Java 8? 有没有办法在Java 8中做到这一点?
Stream.concat(sOne.stream(), sTwo.stream())
您应该知道,在某些情况下,这会降低某些特征IIRC。
You can combine them using: 您可以使用以下方法组合它
List<A> aList = ...;
Stream<String> stream = aList.stream()
.flatMap(a -> Stream.concat(
a.getsOne().stream(),
a.getsTwo().stream())
);
An alternative to already mentioned Stream::concat
is the Stream::of
: 已经提到的
Stream::concat
的替代方案是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>>
. 除非您希望使用
Stream<Stream<T>>
或任何集合Stream<Collection<T>>
的流,否则这需要展平结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.