Java: convert HashMap values to Set<Integer>
Solution 1
Your declaration should be like below. It will convert your map values to Collection
Collection<Set<Integer>> newVariable = myWordDict.values();
Solution 2
Try:
Set<Integer> newVariable = mywordDict.keySet();
or
Set<Integer> newVariable = new HashSet<Integer>(myWordDict.values());
Solution 3
public Set<Map.Entry<K,V>> entrySet()
Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.
If you want iterate over the myWordDict
hash map then just
for(Map.Entry<String, Set<Integer>> entry : myWordDict.entrySet())
{
Set<Integer> newVariable = entry.getValue();
}
Related links
Solution 4
If you need all the values as a Set
of Integers
and not as a Set
of Set
, then you could do something like this
Set<Integer> newVariable = new HashSet<Integer>();
for (Set<Integer> set : myWordDict.values()) {
newVariable.addAll(set);
}
Or if you want them as a Set
of Set
, you need to do something like this
Set<Set<Integer>> newVariable = new HashSet<Set<Integer>>();
newVariable.addAll(myWordDict.values());
Solution 5
flatMap will help you:
myWordDict.values().stream().flatMap(Set::stream).collect(Collectors.toSet());
![TonyGW](https://i.stack.imgur.com/Vn6At.png?s=256&g=1)
Comments
-
TonyGW over 3 years
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
-
TonyGW over 10 yearsvalues() is of Collections type, so there's also data incompatibility problem unless I do an ugly cast.
-
ApproachingDarknessFish over 10 years@TonyGW AFAIK there's no way around that, unless you want to construct the set manually by adding every value from the entry set.
-
TonyGW over 10 yearsI am now using an iterator to iterate through the HashMap value:
-
Rahul over 10 yearsAre you sure this will work?! Firstly, you'll have to cast it and even if you do that, it'll throw a
ClassCastException
. -
aga over 10 years@TonyGW it runs accordingly to the number of entries in your
myWordDict
- if you have 10 entries,for
loop will make 10 iterations.