How to log filtered values in Java Streams

前端 未结 3 550
生来不讨喜
生来不讨喜 2021-02-12 18:49

I have a requirement to log/sysout the filtered values in Java Streams. I am able to log/sysout the non-filtered value using peek() method

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-12 19:25

    As there's no way to run terminal actions on elements matching opposite filters on the same stream, the best option may be just to use a condition in a peek's consumer.

    That avoids traversing the stream/collection twice.

    List persons = Arrays.asList(new Person("John"), new Person("Paul"));
    
    //A consumer that only logs "John" persons
    Consumer logger = p -> {
        if ("John".equals(p.getName())) //condition in consumer
            System.out.println("> " + p.getName());
    };
    

    Then we can pass that consumer to peek, only filtering for the ultimate action after that:

    List nonJohns = persons.stream()
                      .peek(logger)
                      .filter(p -> !"John".equals(p.getName()))
                      .collect(Collectors.toList());
    

提交回复
热议问题