How to log filtered values in Java Streams

前端 未结 3 503
生来不讨喜
生来不讨喜 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:34

    If you want to integrate it with Stream API, there's not much you can do other than introducing the logging manually. The safest way would be to introduce the logging in the filter() method itself:

    List filtered = persons.stream()
          .filter(p -> {
              if (!"John".equals(p.getName())) {
                  return true;
              } else {
                  System.out.println(p.getName());
                  return false;
              }})
          .collect(Collectors.toList());
    

    Keep in mind that introduction of side-effects to Stream API is shady and you need to be aware of what you're doing.


    You could also construct a generic wrapper solution:

    private static  Predicate andLogFilteredOutValues(Predicate predicate) {
        return value -> {
            if (predicate.test(value)) {
                return true;
            } else {
                System.out.println(value);
                return false;
            }
        };
    }
    

    and then simply:

    List persons = Arrays.asList(new Person("John"), new Person("Paul"));
    
    List filtered = persons.stream()
      .filter(andLogFilteredOutValues(p -> !"John".equals(p.getName())))
      .collect(Collectors.toList());
    

    ...or even make the action customizable:

    private static  Predicate andLogFilteredOutValues(Predicate predicate, Consumer action) {
        Objects.requireNonNull(predicate);
        Objects.requireNonNull(action);
    
        return value -> {
            if (predicate.test(value)) {
                return true;
            } else {
                action.accept(value);
                return false;
            }
        };
    }
    

    then:

    List filtered = persons.stream()
      .filter(andLogFilteredOutValues(p -> !"John".equals(p.getName()), System.out::println))
      .collect(Collectors.toList());
    

提交回复
热议问题