Create a stream of values ​​on maps that are values ​​on another map in Java

Sorry for the title of the question; it was hard for me to understand this. If you have a better headline, let me know and I can change it.

I have two types of objects, Bookmark and Revision. I have one big map, for example:

Map<Long, Bookmark> mapOfBookmarks;

it contains key pairs: values ​​like this:

1L: Bookmark1,
2L: Bookmark2,
...

Each bookmark has a getRevisions () method that returns a Map

public Map<Long, Revision> getRevisions();

I want to create a Stream containing all the revisions that exist in mapOfBookmarks. Essentially, I want to do this:

List<Revision> revisions = new ArrayList<>();
for (Bookmark bookmark : mapOfBookmarks.values()) { // loop through each bookmark in the map of bookmarks ( Map<Long, Bookmark> )
    for (Revision revision : bookmark.getRevisions().values()) { // loop through each revision in the map of revisions ( Map<Long, Revision> )
        revisions.add(revision);  // add each revision of each map to the revisions list
    }
}
return revisions.stream(); // return a stream of revisions

However, I would like to do this using Stream functionality, so I like it more:

return mapOfBookmarks.values().stream().everythingElseThatIsNeeded();

What essentially would be how to say:

return Stream.of(revision1, revision2, revision3, revision4, ...);

How would I write this? It should be noted that the data set that it iterates over can be huge, which makes the list method weak.

Windows 7 Java 8

+4
2

flatMap(mapper):

, , .

Stream<Bookmark>, stream(), , , toList().

List<Revision> revisions = 
    mapOfBookmarks.values()
                  .stream()
                  .flatMap(bookmark -> boormark.getRevisions().values().stream())
                  .collect(Collectors.toList());

, , addAll , :

for (Bookmark bookmark : mapOfBookmarks.values()) { // loop through each bookmark in the map of bookmarks ( Map<Long, Bookmark> )
    revisions.addAll(bookmark.getRevisions().values());
}
+3

A flatmap - , . , , , flatmap ,

List<Revision> all =
    mapOfBookmarks.values().stream()
        .flatMap(c -> c.getRevisions().values().stream())
        .collect(Collectors.toList());
+4

All Articles