One more question about HashMap<> in Java:
I have the following
Map<String, Set<Integer>> myWordDict = new HashMap<String, Set<Integer>>();
After storing data into the variable myWordDict
, I want to iterate through the HashMapValues, and add each value to a new Set variable?
When I try to do Set<Integer> newVariable = myWordDict.entrySet()
, it seems the data type is incompatible.
So my question is essentially:
how to convert HashMap values or entrySet() to Set ?
Thanks
It can store different types: Integer keys and String values or same types: Integer keys and Integer values. HashMap is similar to HashTable, but it is unsynchronized. It is allowed to store null keys as well, but there can only be one null key and there can be any number of null values.
You can change either the key or the value in your hashmap, but you can't change both at the same time.
One way to convert is to use the constructor of the ArrayList. In order to do this, we can use the keySet() method present in the HashMap. This method returns the set containing all the keys of the hashmap.
Try:
Set<Integer> newVariable = mywordDict.keySet();
or
Set<Integer> newVariable = new HashSet<Integer>(myWordDict.values());
Your declaration should be like below. It will convert your map values to Collection
Collection<Set<Integer>> newVariable = myWordDict.values();
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