如何在Java Streams中记录过滤后的值 [英] How to log filtered values in Java Streams

查看:50
本文介绍了如何在Java Streams中记录过滤后的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要log/sysout Java Streams中的过滤值.我可以使用peek()方法来log/sysout未过滤的值. 但是,有人可以让我知道如何记录过滤后的值吗?

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. However, can someone please let me know how to log filtered values?

例如,假设我有一个Person对象的列表,如下所示:

For example, let's say I have a list of Person objects like this:

List<Person> persons = Arrays.asList(new Person("John"), new Person("Paul"));

我要过滤掉那些不是约翰"的人,如下:

I want to filter out those persons who are not "John" as follows:

persons.stream().filter(p -> !"John".equals(p.getName())).collect(Collectors.toList());

但是,我必须记录被过滤的那个约翰"人的详细信息.有人可以帮我实现这个目标吗?

However, I have to log the details of that "John" person which is filtered. Can someone please help me achieve this?

推荐答案

如果要将其与Stream API集成,除了手动引入日志记录外,您无能为力.最安全的方法是在filter()方法本身中引入日志记录:

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<Person> filtered = persons.stream()
      .filter(p -> {
          if (!"John".equals(p.getName())) {
              return true;
          } else {
              System.out.println(p.getName());
              return false;
          }})
      .collect(Collectors.toList());

请记住,向Stream API引入副作用是阴暗的,您需要了解自己在做什么.

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 <T> Predicate<T> andLogFilteredOutValues(Predicate<T> predicate) {
    return value -> {
        if (predicate.test(value)) {
            return true;
        } else {
            System.out.println(value);
            return false;
        }
    };
}

然后简单地:

List<Person> persons = Arrays.asList(new Person("John"), new Person("Paul"));

List<Person> filtered = persons.stream()
  .filter(andLogFilteredOutValues(p -> !"John".equals(p.getName())))
  .collect(Collectors.toList());


...甚至使操作可定制:


...or even make the action customizable:

private static <T> Predicate<T> andLogFilteredOutValues(Predicate<T> predicate, Consumer<T> action) {
    Objects.requireNonNull(predicate);
    Objects.requireNonNull(action);

    return value -> {
        if (predicate.test(value)) {
            return true;
        } else {
            action.accept(value);
            return false;
        }
    };
}

然后:

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

这篇关于如何在Java Streams中记录过滤后的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆