Flattening a collection

前端 未结 9 2033
走了就别回头了
走了就别回头了 2020-11-30 02:55

Say I have a Map>

I can get the values of the map easily enough, and iterate over it to produce a single

9条回答
  •  渐次进展
    2020-11-30 03:36

    No, there is no shorter method. You have to use a loop.

    Update Apr 2014: Java 8 has finally come out. In the new version you can use the Iterable.forEach method to walk over a collection without using an explicit loop.

    Update Nov 2017: Found this question by chance when looking for a modern solution. Ended up going with reduce:

    someMap.values().stream().reduce(new ArrayList(), (accum, list) -> {
        accum.addAll(list);
        return accum;
    }):
    

    This avoids depending on mutable external state of forEach(someList::addAll) the overhead of flatMap(List::stream).

提交回复
热议问题