Home » Java » Filter based on condition and collect the object

Filter based on condition and collect the object

Posted by: admin December 28, 2021 Leave a comment

Questions:

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?

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());

###

You can process the current list using removeIf method that accepts a filter predicate:

empList.removeIf(e -> !e.getLanguage().equals("java"));

Or you can copy the current list to another list and do the same.

###

You can also do like this:

List<Object> optionMetas = new ArrayList<>();
Map<Long, Object> optionIdMetaMap_ = optionMetas.stream()
        .filter(option -> option.getXX() || option.getXXX().equal("java"))
        .collect(Collectors.toMap(Object::getKEY, item -> item));

Add your relevant condition in filter().