打印出已过滤流的对象的某些字段

Cso*_*agy 4 java lambda java-8 java-stream

让我们假设有一个Fox类,它有名字,颜色和年龄.让我们假设我有一个狐狸列表,我想打印出那些颜色为绿色的狐狸名字.我想用流来做这件事.

领域:

  • name:私有String
  • color:private String
  • 年龄:私人整数

我编写了以下代码来进行过滤和Sysout:

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

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

问题是什么?我该如何解决?

Ous*_* D. 9

你不能将方法引用与lambdas结合起来,只需使用一个:

foxes.stream()
     .filter(fox -> fox.getColor().equals("green"))
     .forEach(fox -> System.out.println(fox.getName()));
Run Code Online (Sandbox Code Playgroud)

或者其他:

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);
Run Code Online (Sandbox Code Playgroud)

  • @Csongi Nagy什么是方法参考?一种替换/快捷lambda写作的方法.因此,您可以使用它而不是lambda,从不使用lambda.另请注意,并非每个lambdas都可以替换为方法引用.Aomine示例显示了如何使您的需求成为可能. (2认同)

Nic*_*s K 8

只需使用:

foxes.stream().filter(fox -> fox.getColor().equals("green"))
              .forEach(fox -> System.out.println(fox.getName()));
Run Code Online (Sandbox Code Playgroud)

原因是因为您不能一起使用方法引用和lambda表达式.