Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access nested Map entry items in stream?

I have a nested Map object as this:

Map<String,Map<Integer,Double>> items = getMap();

I have a class named MyClass that its constructor is as this:

public MyClass(String city, int month, double average){}

Now I want to convert items to MyClass list as this:

List<MyClass> myList = items.entrySet().stream()
                                       .map(i-> new MyClass(i.getKey(), ?, ?))
                                       .collect(Collectors.toList()); 

but I don't know what should I use instead of ? to access nested Integer and Double values from Map object?

like image 289
Majid Avatar asked Dec 23 '22 03:12

Majid


1 Answers

Since you have a nested map, you have to process the inner map entries too. (this is assuming there are many month-average pairs for a city)

List<MyClass> myList = items.entrySet()
    .stream()
    .flatMap(entry -> entry.getValue().entrySet()
        .stream()
        .map(innerEntry -> new MyClass(entry.getKey(), innerEntry.getKey(), innerEntry.getValue()))
    )
    .collect(Collectors.toList());
like image 55
user7 Avatar answered Dec 28 '22 06:12

user7