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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With