18

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;
buræquete
  • 14,226
  • 4
  • 44
  • 89
user3407267
  • 1,524
  • 9
  • 30
  • 57

2 Answers2

26

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.

Beri
  • 11,470
  • 4
  • 35
  • 57
  • up-vote first, I like this form better than Jacob G's. but the OP who want to collect items into a LinkedList. – holi-java Apr 26 '17 at 06:09
  • [Why is ArrayDeque better than LinkedList](http://stackoverflow.com/questions/6163166/why-is-arraydeque-better-than-linkedlist) – Didier L Apr 26 '17 at 15:40
  • 1
    The reasoning is nonsense. Whether you know the final size of the list, is irrelevant. And even if you are going to do more insert operations than read, the `ArrayList` will be faster in most practical use cases. But even if it is slower in some insertions, you will rarely have write-only data structures in applications, so the subsequent processing will more than compensate the insertion costs, if they really are higher. – Holger Apr 27 '17 at 10:26
17

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()
buræquete
  • 14,226
  • 4
  • 44
  • 89
Jacob G.
  • 28,856
  • 5
  • 62
  • 116