【问题标题】:Printing out some fields of the objects of a filtered stream打印出过滤流对象的一些字段
【发布时间】:2019-01-02 17:55:54
【问题描述】:

假设有一个 Fox 类,它有名字、颜色和年龄。假设我有一个狐狸列表,我想打印出那些狐狸的名字,它们的颜色是绿色的。我想使用流来做到这一点。

字段:

  • 名称:私有字符串
  • 颜色:私有字符串
  • 年龄:私有整数

我已经编写了以下代码来进行过滤和系统输出:

foxes.stream().filter(fox -> fox.getColor().equals("green"))
     .forEach(fox -> System.out::println (fox.getName()));

但是,我的代码中存在一些语法问题。

有什么问题?应该怎么解决?

【问题讨论】:

  • .forEach(fox -> System.out.println (fox.getName()));.map(Fox::getname).forEach(System.out::println);

标签: java lambda java-8 java-stream


【解决方案1】:

您不能将方法引用与 lambdas 组合,只使用一个:

foxes.stream()
     .filter(fox -> fox.getColor().equals("green"))
     .forEach(fox -> System.out.println(fox.getName()));

或其他:

foxes.stream()
     .filter(fox -> fox.getColor().equals("green"))
     .map(Fox::getName) // required in order to use method reference in the following terminal operation
     .forEach(System.out::println);

【讨论】:

  • @Csongi Nagy 什么是方法参考?一种替换/缩短 lambda 写入的方法。所以你可以用它来代替 lambda,永远不要用 lambda。另请注意,并非每个 lambda 都可以被方法引用替换。 Aomine 示例展示了如何满足您的要求。
【解决方案2】:

只需使用:

foxes.stream().filter(fox -> fox.getColor().equals("green"))
              .forEach(fox -> System.out.println(fox.getName()));

原因是你不能同时使用方法引用和 lambda 表达式。

【讨论】:

    【解决方案3】:

    你可以试试:

    foxes.stream().filter(this::isColorGreen).map(Fox::getName).forEach(System.out::println);
    
    
    public boolean isColorGreen(Fox fox) {
        return fox.getColor().equals("green");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 2020-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-27
      相关资源
      最近更新 更多