How to log filtered values in Java Streams

前端 未结 3 506
生来不讨喜
生来不讨喜 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条回答
  •  鱼传尺愫
    2021-02-12 19:21

    You could use

    Map> map = persons.stream()
        .collect(Collectors.partitioningBy(p -> "John".equals(p.getName())));
    System.out.println("filtered: " + map.get(true));
    List result = map.get(false);
    

    or, if you prefer a single-statement form:

    List result = persons.stream()
        .collect(Collectors.collectingAndThen(
            Collectors.partitioningBy(p -> "John".equals(p.getName())),
            map -> {
                System.out.println("filtered: " + map.get(true));
                return map.get(false);
            }));
    

提交回复
热议问题