Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting list of objects with map to array of primitives

I keep finding pieces of something I need to do, but I'm having trouble putting it all together. To start, here is my object, put simply:

Object1
    Object2
        Map<String, Double>

What I need to do is, starting with a list of Object1, get a double[] for the values of the map given a specific key (all Objects in the list have the same N keys in the map).

Here was 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 this is good so far, where do I go from here? If there a better way to do this whole thing, I'm open to suggestions. Any help is appreciated, thank you.

like image 493
MiketheCalamity Avatar asked Jan 27 '26 10:01

MiketheCalamity


1 Answers

Use .mapToDouble to make a DoubleStream:

myList.stream()
    .map(Object1::getObject2)
    .map(Object2::getMyMap)
    .mapToDouble(m -> m.get(key))  // or throw if key is not in map
    .toArray();
like image 154
Misha Avatar answered Jan 29 '26 00:01

Misha