Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
like image 337
ybonda Avatar asked Jun 01 '17 07:06

ybonda


People also ask

Can a list be nested in another list?

A list can contain any sort object, even another list (sublist), which in turn can contain sublists themselves, and so on. This is known as nested list. You can use them to arrange data into hierarchical structures. You can access individual items in a nested list using multiple indexes.

Can you have a list within a list Python?

Python list can contain sub-list within itself too. That's called a nested list.

Is a nested list a list?

A nested list is a list of lists, or any list that has another list as an element (a sublist). They can be helpful if you want to create a matrix or need to store a sublist along with other data types.


1 Answers

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

like image 73
Eugene Avatar answered Oct 12 '22 12:10

Eugene