How to add everything using java threads?

How can I add everything using java 8?

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

At the moment I am doing:

List<Item> itemList = Lists.newLinkedList();
for (Map<Item, Boolean> entry : processeditemList.values()) {
    itemList.addAll(entry.keySet());
}
return itemList;
+4
source share
2 answers

You can use flatMap . It was used to combine several threads into one. Therefore, 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 the default implementation of the list, you can use below the collector:

Collectors.toCollection(LinkedList::new)

A LinkedList would be nice if you don't know the final size of the list, and you do more insert operations than you think.

ArrayList oposite: /. ArrayList , , .

+9

, , , Stream:

processeditemList.values().stream()
    .flatMap(e -> e.keySet().stream())
    .collect(Collectors.toCollection(LinkedList::new));

, Javadocs - , .

: , . , List ,

Collectors.toCollection(LinkedList::new)

Collectors.toList()
+10

Source: https://habr.com/ru/post/1675672/


All Articles