How to do add all with java streams?

user3407267 :

How do I do add all with java 8 ?

processeditemList is a Map<Integer, Map<Item, Boolean>> 

As for now I am doing :

List<Item> itemList = Lists.newLinkedList();
for (Map<Item, Boolean> entry : processeditemList.values()) {
    itemList.addAll(entry.keySet());
}
return itemList;
Beri :

You can use flatMap. It's used to combine multiple streams into a single one. So here you need to create a stream of collections, and then create a stream from each of them:

processeditemList.values().stream()
    .map(Map::keySet)     // Stream<Set<Item>>
    .flatMap(Set::stream) // convert each set to a stream
    .collect(toList());   // convert to list, this will be an ArrayList implmentation by default

If you want to change default List implementation, then you can use below collector:

Collectors.toCollection(LinkedList::new)

LinkedList would be good if you do not know the final size of the list, and you do more insert operations than read.

ArrayList is the oposite: more you read, and less add/remove. Because ArrayList under the hood holds an array, which must be rescaled when adding new elements, but never get's reduced, when you remove elements.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=439420&siteId=1