3

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.

1 Answer 1

7

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();
Sign up to request clarification or add additional context in comments.

4 Comments

Careful with null values.
To not throw, do this: myList.stream().map(o -> o.getObject2().getMyMap().get(key)).filter(d -> d != null).mapToDouble(Double::doubleValue).toArray()
Based on OP's description, throwing is probably more appropriate. If one of the maps is missing the key, the data is invalid and the code should fail fast rather than return a shorter array.
Or maybe mapToDouble(m -> m.getOrDefault(key, 0.0)). Who knows? We are speculating here. Let's let the OP decide what's better when there's no entry for the given key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.