Nested lists with streams in Java8

前端 未结 4 1261
感动是毒
感动是毒 2020-12-05 23:42

I have a list of objects A. Each object A in this list contains list of object B and the object B contains list of Object C. The object C contains an attribute name that i w

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 00:23

    I had same task but i had one nested class. And I had to filter the objects with filter in the nested collection. As a result, I had to get items that have matches in the collection.

    for example:

    public class RootElement {
        private String name;
        private List nestedElements;
    
        //getters / setters and constructors
    }
    

    init collection with elements:

    List elements = Arrays.asList(
                    new RootElement("first", Arrays.asList("one", "two", "three")),
                    new RootElement("second", Arrays.asList("four", "one", "two")));
    

    filter example:

    String filterParam = "four";
            List filtered = elements.stream()
                    .flatMap(root -> root.getNestedElements()
                            .stream()
                            .filter(nested -> nested.equalsIgnoreCase(filterParam))
                            .map(filteredElement -> new RootElement(root.getName(), root.getNestedElement())))
                    .collect(Collectors.toList());
    

    Hope it will help someone.

提交回复
热议问题