如何使用 Java 8 / 流 API 列出、映射和“打印 if count>0”?

这是我现在的代码。


List<Cat> cats = petStore.getCatsForSale();


if (!cats.empty) 

    logger.info("Processing for cats: " + cats.size());


for (Cat cat : cats) {

    cat.giveFood();

}

我的同事使用 Java 流 API 编写了非常好的代码。我试图将它重写为一个流式语句,但我被卡住了。


petStore.getCatsForSale().stream.forEach(cat -> cat.giveFood)

    .countTheCats().thenDo(logger.info("Total number of cats: " + x)); // Incorrect... is this possible?

我怎样才能做到这一点?理想情况下,我想要一个流式声明......


弑天下
浏览 97回答 3
3回答

慕桂英546537

您当前的代码在没有流的情况下要好得多,并且可以进一步缩短为:if (!cats.isEmpty()) {&nbsp; &nbsp; logger.info("Processing for cats: " + cats.size());}cats.forEach(Cat::giveFood); // Assuming giveFood is a stateless operation

茅侃侃

我不确定为什么要在当前循环解决方案中使用流,但您也可以使用Stream<List<Cat>>:Stream.of(petStore.getCatsForSale())&nbsp; &nbsp; .filter(cats -> !cats.isEmpty())&nbsp; &nbsp; .flatMap(cats -> {&nbsp; &nbsp; &nbsp; &nbsp; logger.info("Processing for cats: " + cats.size());&nbsp; &nbsp; &nbsp; &nbsp; return cats.stream();&nbsp; &nbsp; })&nbsp; &nbsp; .forEach(Cat::giveFood);也许是优化:Stream.of(petStore.getCatsForSale())&nbsp; &nbsp; .filter(cats -> !cats.isEmpty())&nbsp; &nbsp; .peek(cats -> logger.info("Processing for cats: " + cats.size()))&nbsp; &nbsp; .flatMap(Collection::stream)&nbsp; &nbsp; .forEach(Cat::giveFood);或使用其他变体:Stream.of(petStore.getCatsForSale())&nbsp; &nbsp; .filter(cats -> !cats.isEmpty())&nbsp; &nbsp; .mapToInt(cats -> {&nbsp; &nbsp; &nbsp; &nbsp; cats.forEach(Cat::giveFood);&nbsp; &nbsp; &nbsp; &nbsp; return cats.size();&nbsp; &nbsp; })&nbsp; &nbsp; .findAny()&nbsp; &nbsp; .ifPresent(count -> logger.info("Processing for cats: " + count));

德玛西亚99

cats.stream() &nbsp;&nbsp;&nbsp;&nbsp;.peek(Cat::giveFood) &nbsp;&nbsp;&nbsp;&nbsp;.findAny().ifPresent(cat&nbsp;->&nbsp;logger.info("Processing&nbsp;for&nbsp;cats:&nbsp;"&nbsp;+&nbsp;cats.size()));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java