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;
Using Stream.collect() The second method for calculating the sum of a list of integers is by using the collect() terminal operation: List<Integer> integers = Arrays. asList(1, 2, 3, 4, 5); Integer sum = integers. stream() .
One approach is to use a terminal operation to collect the values of the stream to an ArrayList, and then simply use add(int index, E element) method. Keep in mind that this will give you the desired result but you will also lose the laziness of a Stream because you need to consume it before inserting a new element.
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.
I'm on my phone at the moment so I can't promise that this will be syntactically perfect, but here's how you can do it with a Stream
:
processeditemList.values().stream()
.flatMap(e -> e.keySet().stream())
.collect(Collectors.toCollection(LinkedList::new));
I'm unable to test it currently, but I'll look over the Javadocs and change anything if it's incorrect.
Edit: I think everything is good. If it doesn't matter which List
implementation is used, you can change
Collectors.toCollection(LinkedList::new)
to
Collectors.toList()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With