ybonda
ybonda

Reputation: 1710

Filter a list with condition on inner list

I have a list of objects. Each object contains another list. I want to filter the list with condition on inner list.

For example:

There is a list of factories. Each factory contains a list of different car models it produces. I want to filter factory list in such way that I will get only factories that produce Mazda3.

How can I do it with lambda?

It should be something similar to this:

factories.stream().filter(f -> f.getCars().stream().filter(c -> C.getName().equals("Mazda3")).).collect(Collectors.toList());

Upvotes: 8

Views: 1317

Answers (2)

Hugues M.
Hugues M.

Reputation: 20467

Here is something that should do:

factories.stream()
         .filter(factory -> factory.getCars().stream()
                           .anyMatch(car -> searchedName.equals(car.getName())))
         .collect(Collectors.toList())

But it would be better design if you could add a specific method on your factory class:

factories.stream()
         .filter(factory -> factory.hasProduced(model))
         .collect(Collectors.toList())

See also "runnable" example online -- as is it only shows that the methods pass compilation, not a full demo with data, but you can do that yourself in your own code, so... ;)

Upvotes: 7

Eugene
Eugene

Reputation: 120848

If I understood correctly(and simplified your example)

 List<List<Integer>> result = Arrays.asList(
                       Arrays.asList(7), 
                       Arrays.asList(1, 2, 3), 
                       Arrays.asList(1, 2, 4), 
                       Arrays.asList(1, 2, 5))
            .stream()
            .filter(inner -> inner.stream().anyMatch(x -> x == 5))
            .collect(Collectors.toList());

    System.out.println(result); // only the one that contains "5"[[1,2,5]] 

EDIT

After seeing your example you are looking for anyMatch

Upvotes: 10

Related Questions