Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use java 8 streams to get values from my hashmap [duplicate]

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());
like image 985
DanielD Avatar asked Apr 12 '26 23:04

DanielD


1 Answers

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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!