2

I have a hashmap that looks something like this:

Map<String, ImageRecipeMap> contentIdToImageIdsMap = new HashMap<>();

my ImageRecipeMap object looks something like this:

public class ImageRecipeMap {

    private ContentType contentType;

    private List<String> imageIds;

    public List<String> getImageIds() {
        return imageIds;
    }

    public void setImageIds(List<String> imageIds) {
        this.imageIds = imageIds;
    }

    ...
}

I want to grab all the Lists of imageIds and create a total imageIds list using java 8 streams. This is what I have so far, but I seem to have a compile error on my collect:

List<String> total = contentIdToImageIdsMap.values().stream()
           .map(value -> value.getImageIds())
           .collect(Collectors.toList());
DanielD
  • 1,315
  • 4
  • 17
  • 25

1 Answers1

4

Your solution returns List<List<String>>. Use .flatMap() to flatten them like this.

    List<String> total = contentIdToImageIdsMap.values().stream()
           .flatMap(value -> value.getImageIds().stream())
           .collect(Collectors.toList());

.flatMap() changes Stream<List<String>> to Stream<String>.

  • yes, that looks like it did the trick. Can you explain what the difference between flatMap and map is? And why would my ids be converted into another stream? Thanks – DanielD Mar 08 '16 at 06:45
  • 3
    getImageIds().stream() will create a Stream object for each element in your map. With map, you would have a Stream> or a _stream composed of stream of strings_. flatMap will _glue_ all the streams of strings together into a single stream and give you a simple Stream – superbob Mar 08 '16 at 07:22