103

I have the following situation

Map<Key, ListContainer> map; 

public class ListContainer {
  List<AClass> lst;
}

I have to merge all the lists lst from the ListContainer objects from a Map map.

public static void main(String[] args) {
   List<AClass> alltheObjectsAClass = map.values().stream(). // continue....    
}

Any idea how, using Java 8 stream API?

3
  • Can you provide an example what you mean with merging? Say your map is {a: [1,2], b[3,4]}, do you want to chain them, like [1,2,3,4], or make a list of lists, [[1,2],[3,4]], or zip them [[1,3],[2,4]]? Also, you are aware that a Map has no order, are you? Commented Apr 16, 2014 at 14:56
  • @tobias_k I want the result to be [1,2,3,4], unsorted! Commented Apr 16, 2014 at 15:06
  • If ListContainer only wraps a List<T> then you can replace Map<Key, ListContainer> with Map<Key, List<T>> Commented Dec 29, 2016 at 13:52

5 Answers 5

216

I think flatMap() is what you're looking for.

For example:

 List<AClass> allTheObjects = map.values()
         .stream()
         .flatMap(listContainer -> listContainer.lst.stream())
         .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

6 Comments

? Why were the comments deleted that explained why .flatMap(Collection::stream) is not possible here?
@Puce good question, however it's kind-of possible: if ListContainer is encapsulated (i.e. has a getter for lst), you can decompose .flatMap(->) into .map(ListContainer::getLst) .flatMap(Collection::stream)
@TWiStErRob Yes, that is what I wrote in my original comment. Why was it deleted?
@Puce a note in your answer explaining why .flatMap(Collection::stream) is no possible would be better, I think. Should be more permanent.
@Alex yes, this is one way resp. .map(listContainer -> listContainer.lst).filter(Objects::nonNull).flatMap(Collection::stream)
|
79

Alternative: Stream.concat()

Stream.concat(map.values().stream(), listContainer.lst.stream())
                             .collect(Collectors.toList()

1 Comment

plus 1 even though it does not answer the question, it answers the title of the question
8

Already answered above, but here's another approach you could take. I can't find the original post I adapted this from, but here's the code for the sake of your question. As noted above, the flatMap() function is what you'd be looking to utilize with Java 8. You can throw it in a utility class and just call "RandomUtils.combine(list1, list2, ...);" and you'd get a single List with all values. Just be careful with the wildcard - you could change this if you want a less generic method. You can also modify it for Sets - you just have to take care when using flatMap() on Sets to avoid data loss from equals/hashCode methods due to the nature of the Set interface.

Edit - If you use a generic method like this for the Set interface, and you happen to use Lombok, make sure you understand how Lombok handles equals/hashCode generation.

  /**
    * Combines multiple lists into a single list containing all elements of
    * every list.
    * 
    * @param <T> - The type of the lists.
    * @param lists - The group of List implementations to combine
    * @return a single List<?> containing all elements of the passed in lists.
    */
   public static <T> List<?> combine(final List<?>... lists) {
      return Stream.of(lists).flatMap(List::stream).collect(Collectors.toList());
   }

Comments

3

In Java 8 we can use stream List1.stream().collect(Collectors.toList()).addAll(List2); Another option List1.addAll(List2)

Comments

3

To merge several lists or other types of collections into a single one you can use this approach:

Stream.of(list1.stream(), list2.stream(), someSet.stream(), otherCollection.stream())
    .flatMap(Function.identity())
    .collect(Collectors.toList());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.