How to access nested Map entry items in stream?

Majid :

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?

user7 :

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());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=73507&siteId=1