Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering a list using Java 8 lambda expressions

I have a Project class:

class Project {
    List<Name> names;
    int year;
    public List<Name> getNames(){
        return names;
    }
}

Then I have another main function where I have a List<Project> and have to filter that list of projects on the basis of year and get names list as the result.

Can you please tell me how to do it using java 8 lambda expressions?

Thanks

like image 201
Suvriti Gandhi Avatar asked Dec 26 '17 10:12

Suvriti Gandhi


People also ask

Can Java 8 have 2 filters?

Performance. We have seen that using multiple filters can improve the readability of our code.


1 Answers

Well, you didn't state the exact filtering condition, but assuming you wish to filter elements by a given year:

List<Name> names = projects.stream()
    .filter(p -> p.getYear() == someYear) // keep only projects of a 
                                         // given year
    .flatMap(p -> p.getNames().stream()) // get a Stream of all the
                                        // Names of all Projects
                                        // that passed the filter
    .collect(Collectors.toList());     // collect to a List
like image 149
Eran Avatar answered Oct 19 '22 10:10

Eran