Java: convert HashMap values to Set<Integer>

56,680

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

What does entrySet returns?

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());
Share:
56,680
TonyGW
Author by

TonyGW

Too lazy to write anything about myself

Updated on October 27, 2020

Comments

  • TonyGW
    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
    TonyGW over 10 years
    values() is of Collections type, so there's also data incompatibility problem unless I do an ugly cast.
  • ApproachingDarknessFish
    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
    TonyGW over 10 years
    I am now using an iterator to iterate through the HashMap value:
  • Rahul
    Rahul over 10 years
    Are you sure this will work?! Firstly, you'll have to cast it and even if you do that, it'll throw a ClassCastException.
  • aga
    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.