eclipse-collections icon indicating copy to clipboard operation
eclipse-collections copied to clipboard

Add getOptional or equivalent to primitive maps

Open victornoel opened this issue 5 years ago • 6 comments

Hi,

When dealing with a primitive map (e.g., ObjectDoubleMap), it is possible to call getIfAbsent(key, defaultValue) to get a default value when key is missing, but it is not possible to get the value OR know it is absent in one call.

I suppose something like getOptional that would return a OptionalDouble would make sense, though I'm not sure there are optional types for all primitives, but maybe we can introduce them too?

victornoel avatar Sep 04 '20 14:09 victornoel

This API will be great to have! But why only for ObjectPrimitiveMap? Do we need something similar for maps in-general to return an Optional?

nikhilnanivadekar avatar Sep 04 '20 14:09 nikhilnanivadekar

@nikhilnanivadekar hehe yes. Well, actually MapIterable already has it, so it is only for primitive maps, but yes, all of them. I was too narrow minded well I wrote the description, I've updated it :)

victornoel avatar Sep 04 '20 15:09 victornoel

Perfect! I think we should just have getOptional() instead of labeling it with a particular primitive. That way the API is consistent with MapIterable.

nikhilnanivadekar avatar Sep 04 '20 15:09 nikhilnanivadekar

The only downside of this is as @victornoel points out there are only Optional<T>, OptionalInt, OptionalLong and OptionalDouble in JDK. I am not sure it would be a good idea to introduce new Optionals for other primitives in EC, especially with the possibility of generic specialization for primitives being an eventual possibility.

Possible Options:

  1. Limit to Int, long, double map varieties
  2. Widen types for byte, short, char, float (option for boolean?)
  3. Box with Optional<T>
  4. Introduce new Optional types for missing types

Thoughts?

donraab avatar Sep 04 '20 17:09 donraab

We should just box the ones not supported by JDK

nikhilnanivadekar avatar Sep 04 '20 17:09 nikhilnanivadekar