Converting a list of objects with a map to an array of primitives
I keep finding pieces of something that I need to do, but I'm having trouble getting it. For starters, here's my object, just:
Object1
Object2
Map<String, Double>
What I need to do, starting with a list Object1
, get double[]
for the map values โโgiven by a specific key (all objects in the list have the same N keys in the map).
Here's my starting attempt:
myList.stream().map(Object1::getObject2).map(Object2::getMyMap).map(m -> m.get(key).collect(Collectors.toCollection(ArrayList::new))
I'm not sure how to get to the primitive array from here. If it's okay so far, where do I go from here? If there is a better way to do all this, I am open to suggestions. Any help is appreciated, thanks.
+3
user3499973
source
to share
1 answer
Use .mapToDouble
to do DoubleStream
:
myList.stream()
.map(Object1::getObject2)
.map(Object2::getMyMap)
.mapToDouble(m -> m.get(key)) // or throw if key is not in map
.toArray();
+7
Misha
source
to share