代码之家  ›  专栏  ›  技术社区  ›  vikingsteve

如何使用Java8/StreamAPI列出、映射和“如果计数>0则打印”?

  •  17
  • vikingsteve  · 技术社区  · 6 年前

    这是我现在的代码。

    List<Cat> cats = petStore.getCatsForSale();
    
    if (!cats.empty) 
        logger.info("Processing for cats: " + cats.size());
    
    for (Cat cat : cats) {
        cat.giveFood();
    }
    

    petStore.getCatsForSale().stream.forEach(cat -> cat.giveFood)
        .countTheCats().thenDo(logger.info("Total number of cats: " + x)); // Incorrect... is this possible?
    

    我该怎么做?理想情况下,我想要一个流式语句。。。

    4 回复  |  直到 6 年前
        1
  •  18
  •   Naman    4 年前

    如果没有流,您当前的代码会更好,并且可以进一步缩短为:

    if (!cats.isEmpty()) {
        logger.info("Processing for cats: " + cats.size());
    }
    cats.forEach(Cat::giveFood); // Assuming giveFood is a stateless operation
    
        2
  •  11
  •   Peter Mortensen icecrime    6 年前

    为什么? Stream<List<Cat>>

    Stream.of(petStore.getCatsForSale())
        .filter(cats -> !cats.isEmpty())
        .flatMap(cats -> {
            logger.info("Processing for cats: " + cats.size());
            return cats.stream();
        })
        .forEach(Cat::giveFood);
    

    可能是一种优化:

    Stream.of(petStore.getCatsForSale())
        .filter(cats -> !cats.isEmpty())
        .peek(cats -> logger.info("Processing for cats: " + cats.size()))
        .flatMap(Collection::stream)
        .forEach(Cat::giveFood);
    

    或者使用另一种变体:

    Stream.of(petStore.getCatsForSale())
        .filter(cats -> !cats.isEmpty())
        .mapToInt(cats -> {
            cats.forEach(Cat::giveFood);
            return cats.size();
        })
        .findAny()
        .ifPresent(count -> logger.info("Processing for cats: " + count));
    
        3
  •  4
  •   Oleg Cherednik    6 年前
    cats.stream()
        .peek(Cat::giveFood)
        .findAny().ifPresent(cat -> logger.info("Processing for cats: " + cats.size()));
    
        4
  •  2
  •   Peter Mortensen icecrime    6 年前

    我同意 with @Lino

    List<Cat> cats = petStore.getCatsForSale();
    
    cats.stream().limit(1)
        .flatMap(c -> {
            logger.info("Processing for cats: " + cats.size());
            return cats.stream();
        }).forEach(Cat::giveFood);