Java流:可选流

时间:2018-12-20 15:29:45

标签: java java-stream optional

这是我的代码:

INSERT INTO my_table (COL1, COL2, ... DATE_, QUARTER_, YEAR_)
SELECT sr.COL1, sr.COL2, .... 
TO_DATE(TO_CHAR(TO_DATE(SUBSTR(sr.ALL_PERIODS, -8), 'mm/dd/yy'), 'YYYY-MM-DD'), 'YYYY-MM-DD') DATE_,
CASE SUBSTR(sr.ALL_PERIODS, 1, 3)
WHEN 'JFM' THEN 1 
WHEN 'AMJ' THEN 2
WHEN 'JAS' THEN 3
WHEN 'OND' THEN 4
END QUARTER_,
'20'||SUBSTR(sr.ALL_PERIODS, 5,2) YEAR_,
FROM SOURCE_TABLE sr
[WHERE sr.COL99 = 'Y'];

其中Optional<Application> application = this.applicationDao.findById(id); 类是:

Application

我需要像这样从返回public class Application { private String code; private Collection<ApplicationQuote> quotes; } 创建一个流:

Optional<Application>

每个(app, quote-1) > (app, quote-2) > ... > (app, quote-n) 位于其中的地方都返回quote-n

我希望我解释得很好。

到目前为止,我已经能够编写此代码,但对此我并不感到满意:

Optional<Application>.quotes

3 个答案:

答案 0 :(得分:3)

您在这里过于复杂。也就是说,您实际上并不需要将app.quotes包裹到一个可选的内容中,只需检查它是否为非null(实际上滥用了Optional的主要目的)等。

因为您想要Stream<Pair<Application, ApplicationQuote>>,所以可以按照以下步骤操作:

JDK8:

application.filter(app -> app.getQuotes() != null)
           .map(Stream::of).orElseGet(Stream::empty)
           .flatMap(app -> app.getQuotes().stream().map(quote -> Pair.of(app, quote)));

JDK9:

application.filter(app -> app.getQuotes() != null).stream()
           .flatMap(app -> app.getQuotes().stream().map(quote -> Pair.of(app, quote)));

答案 1 :(得分:1)

Optional.orElse

理想情况下,您当前拥有的是 Optional<Stream<Pair<Application, ApplicationQuote>>> optionalPairStream ,而您可能正在寻找的只是添加一个默认大小写,而仅将Stream设为:

Stream<Pair<Application, ApplicationQuote>> pairStream = application
        .map(app -> Pair.of(app, Optional.ofNullable(app.getQuotes())))
        .filter(quote -> quote.getValue().isPresent())
        .map(quote -> quote.getValue().get().stream().map(q -> Pair.of(quote.getKey(), q)))
        .orElse(Stream.empty());

Optional.stream

使用Java9,您可以将以下代码更新为:

Stream<Pair<Application, ApplicationQuote>> pairStream = application
           .map(app -> Pair.of(app, Optional.ofNullable(app.getQuotes())))
           .filter(quote -> quote.getValue().isPresent())
           .stream() // new API
           .flatMap(quote -> quote.getValue().orElse(Collections.emptyList())
                   .stream().map(q -> Pair.of(quote.getKey(), q)));

答案 2 :(得分:0)

像这样?

Optional<Pair<String,List<String>> quotesForApp = 
     app.map(a -> a.getQuotes()
                     .stream()
                     .map(Quote::getValue())
                     .collect(toList()) // optional list of quotes now
        // we can call app.getCode() safely, or we wouldn't be mapping
        .map(quotes -> Pair.of(app.getCode(), quotes));