Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do add all with java streams?

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;
like image 548
user3407267 Avatar asked Apr 26 '17 05:04

user3407267


People also ask

How do I add all elements to a stream List?

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() .

How do you add value to a 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.


2 Answers

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.

like image 140
Beri Avatar answered Sep 18 '22 13:09

Beri


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()
like image 34
Jacob G. Avatar answered Sep 19 '22 13:09

Jacob G.