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

领域:

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

  • 我编写了以下代码来进行过滤和 Sysout:
    foxes.stream().filter(fox -> fox.getColor().equals("green"))
         .forEach(fox -> System.out::println (fox.getName()));
    

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

    问题是什么?我该如何整理?

    最佳答案

    您不能将方法引用与 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);
    

    关于java - 打印出过滤流的对象的一些字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54010975/

    10-09 19:23