Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

duplicate key value pairs [duplicate]

Is there a native data structure in java that accepts key value pairs and allows duplicates? I am creating a checklist of characters in a string but some characters occur more than once.

ex

j -> false
a -> false
v -> false
a -> false
like image 559
Liondancer Avatar asked Dec 07 '22 03:12

Liondancer


1 Answers

You can simulate multiple key-value (KV) pairs by saving a list of values for each in a map. This is a standard implementation approach for "multivalue" maps.

So, if the key is a Character object and the value is Boolean, you can do

Map<Character, List<Boolean>> multimap = new HashMap<Character, List<Boolean>>();

and every time you want to add a new value to an existing KV pair in the map just call

multimap.get(key).add(value);

where key is the Character and value its corresponding Boolean value.

The Guava library by Google (free download) has a Multimap interface implemented in various ways, so essentially you can instantiate a MultiMap<Character, Boolean> map and use it accordingly. Similarly, you can get the Apache Commons Collections library and use its MultiValueMap class. You may also want to check the answers to a similar StackOverflow question, or another one.

If you only want to store one of each value per key, then a Set should be used in the place of the List.

like image 80
PNS Avatar answered Dec 14 '22 18:12

PNS