Best way to store a complex key in a map?

Viewed 33

In java, keys of a Map work great if they are primitive, but it can be more complicated if they are not. For a Map<String, Payload> we are comparing primitive types and so if do a map.put("key1", payload1), followed by a map.get("key1"), I"ll get my key.

This wouldn't work if my key is of the type Map<MyEnumKey, Payload>, unless I override the equals and hashCode methods.

In my situation, the key I have currently is an enum like this:

Map<MyEnumKey, String> map = Map.of(
    MyEnumKey.FIRST_KEY, "payload1"
    MyEnumKey.SECOND_KEY, "payload2"
);

But I'd like the map to be able to store more than 1 enum as the key. So something like a List<MyEnumKey> makes sense.

Map<..., String> map = Map.of(
    (MyEnumKey.FIRST_KEY, MyEnumKey.SOME_KEY), "payload1"
    MyEnumKey.SECOND_KEY, "payload2"
);

In this situation, what can be the best way to define the map without creating a separate class that encapsulates a List<MyEnumKey> and then overriding the equals and hashcode? Can this be solved in a "functional" manner?

1 Answers
Map<List<EnumKey>, String> someMap

Should do the trick.

Related