Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

stream - Java 11: How to summarize two Single<Optional<>> in java?

Help please, How to summarize two Single<Optional> in java 11 ?

I am using RxJava but I don't think it means anything.

for example:

Single<Optional<MonetaryAmount>> first = someMethod1(a, b);
Single<Optional<MonetaryAmount>> second = someMethod2(a, b);

I want to do something like this not syntactically but logically

Single<Optional<MonetaryAmount>> result = first + second;

I tried to do something like this but it doesn't work in java 11

Single<Optional<MonetaryAmount>> result = Stream.concat(first, second)
                                                .reduce(MonetaryAmount::sum);

Do you have some idea ?

question from:https://stackoverflow.com/questions/65916695/java-11-how-to-summarize-two-singleoptional-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use concatMapSingle and mapOptional to get to the present values:

Observable<Single<Optional<MonetaryAmount>>> amounts = 
    Observable.fromArray(first, second);

amounts.concatMapSingle(v -> v)
.mapOptional(v -> v) // RxJava 3
.reduce(MonetaryAmount::sum)
;

For RxJava 2, use a filter+map combo:

.filter(Optional::isPresent)
.map(Optional::get)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...