Getting only required objects from a list using Java 8 Streams

前端 未结 3 2051
余生分开走
余生分开走 2021-02-14 19:12

Consider a Parent class with the attributes attrib1, attrib2 and List child with its corresponding getters and s

3条回答
  •  渐次进展
    2021-02-14 19:23

    I know the question is almost 2 years old, but hopefully this answer can help someone.

    There's a library called com.coopstools.cachemonads. It extends the java stream (and Optional) classes to allow caching of entities for later use.

    The solution can be found with:

    List goodParents = CacheStream.of(parents)
                .cache()
                .map(Parent::getChildren)
                .flatMap(Collection::stream)
                .map(Child::getAttrib1)
                .filter(att -> att > 10)
                .load()
                .distinct()
                .collect(Collectors.toList());
    

    where, parents is an array or stream.

    For clarity, the cache method is what stores the parents; and the load method is what pulls the parents back out. And If a parent does not have children, a filter will be needed after the first map to remove the null lists.

    This library can be used in any situation where operations need to be performed on children, including map/sort/filter/etc, but where an older entity is still needed.

    The code can be found at https://github.com/coopstools/cachemonads (where I've included your example in the readme), or can be downloaded from maven:

    
        com.coopstools
        cachemonads
        0.2.0
    
    

    (or, gradle, com.coopstools:cachemonads:0.2.0)

提交回复
热议问题