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.
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);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With