Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing out some fields of the objects of a filtered stream

Let's suppose there is a Fox class, which has got name, color and age. Let's assume that I have a list of foxes, and I want to print out those foxes' names, whose colours are green. I want to use streams to do so.

Fields:

  • name: private String
  • color: private String
  • age: private Integer

I have written the following code to do the filtering and Sysout:

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

However, there are some syntax issues in my code.

What is the problem? How should I sort it out?

like image 869
lyancsie Avatar asked Jan 02 '19 17:01

lyancsie


2 Answers

You cannot combine method references with lambdas, just use one:

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

or the other:

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);
like image 144
Ousmane D. Avatar answered Oct 13 '22 11:10

Ousmane D.


Simply use :

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

The reason is because you cannot use method references and lambda expressions together.

like image 34
Nicholas Kurian Avatar answered Oct 13 '22 10:10

Nicholas Kurian