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?
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With