Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Stream filter nested objects return top level fields

I have a following hierarchy in my model:

class Item {
    String name;
    ...
    List<SubItem> subItems;
}

class SubItem {
    String name;
    ...
    List<String> ids;
}

I'd like to find an Item and its SubItem where subItem.ids list contains some specific id and return a Pair of Item.name and SubItem.name. I assume all names and ids are unique, so I'm interested only in the first result.

I can do this using two foreach loops:

for (Item item : items) {
    for (SubItem subItem : item.subItems) {
        if (subItem.ids.contains("some value")) {
            return Pair<String, String>(item.name, subItem.name)
        }
    }
}

I was wondering if I can achieve the same result using Java 8 Streams?

I found this answer How to filter nested objects with Stream, but I need to return some top level fields (names) as well.

like image 663
pawello2222 Avatar asked Sep 19 '25 17:09

pawello2222


1 Answers

You can use flatMap:

return items.stream()
            .flatMap(i -> i.getSubItems()
                           .stream()
                           .filter(si -> si.ids.contains("some value"))
                           .map(si -> new Pair<String, String>(i.name, si.name)))
            .findFirst()
            .orElse(null);
like image 74
Eran Avatar answered Sep 22 '25 06:09

Eran