Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter based on condition and collect the object

In java 8, collect emp object based on some filter condition.

In main class:

List<Emp> empList = Arrays.asList(
    new Emp("aaa", language1), 
    new Emp("cc", language2),
    new Emp("bb", language3), 
    new Emp("dd", language3)
);

empList.stream()
    .flatMap(s->s.getLanguage().stream())
    .filter(s->s.equals("java"))
    .forEach(System.out::println); //Here just i am printing. 

Actually I need to collect new List<EMP>.

How to collect emp object that are all have language "java". How can I do this?

like image 202
Learn Hadoop Avatar asked Dec 13 '17 07:12

Learn Hadoop


People also ask

What is collection filter?

Filtering is one of the most popular tasks in collection processing. In Kotlin, filtering conditions are defined by predicates – lambda functions that take a collection element and return a boolean value: true means that the given element matches the predicate, false means the opposite.

What method is used to filter elements from a collection?

Java 8 Stream interface introduces filter() method which can be used to filter out some elements from object collection based on a particular condition. This condition should be specified as a predicate which the filter() method accepts as an argument. The java. util.

How do I filter a list based on another list in Java 8?

After populating both the lists, we simply pass a Stream of Employee objects to the Stream of Department objects. Next, to filter records based on our two conditions, we're using the anyMatch predicate, inside which we have combined all the given conditions. Finally, we collect the result into filteredList.

How do you filter an object in an array?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.


1 Answers

You should not use flatMap if you want to collect Emp objects in the end because it will change every element to something else and it can be quite hard to map them back.

You should put all your logic in a filter: "keep the Emp object if getLanguage contains "java"".

empList.stream()
    .filter(x->x.getLanguage().contains("java"))
    .collect(Collectors.toList());
like image 90
Sweeper Avatar answered Sep 24 '22 09:09

Sweeper