Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: convert HashMap values to Set<Integer>

Tags:

java

hashmap

set

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

like image 252
TonyGW Avatar asked Nov 12 '13 06:11

TonyGW


People also ask

Can HashMap key be an integer?

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.

Can you change HashMap values?

You can change either the key or the value in your hashmap, but you can't change both at the same time.

Can we convert HashMap to array?

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.


2 Answers

Try:

Set<Integer> newVariable = mywordDict.keySet();

or

Set<Integer> newVariable = new HashSet<Integer>(myWordDict.values());
like image 119
Kamlesh Arya Avatar answered Sep 30 '22 21:09

Kamlesh Arya


Your declaration should be like below. It will convert your map values to Collection

  Collection<Set<Integer>> newVariable = myWordDict.values();
like image 25
Masudul Avatar answered Sep 30 '22 21:09

Masudul