5

I have a method that goes through the possible states in a board and stores them in a HashMap

void up(String str){
  int a = str.indexOf("0");
  if(a>2){
   String s = str.substring(0,a-3)+"0"+str.substring(a-2,a)+str.charAt(a-3)+str.substring(a+1);
   add(s,map.get(str)+1);
   if(s.equals("123456780")) {
    System.out.println("The solution is on the level  "+map.get(s)+" of the tree");

        //If I get here, I need to know the keys on the map
       // How can I store them and Iterate through them using 
      // map.keySet()?

   }
  }

}

I'm interested in the group of keys. What should I do to print them all?

HashSet t = map.keySet() is being rejected by the compiler as well as

LinkedHashSet t = map.keySet()
andandandand
  • 21,946
  • 60
  • 170
  • 271

9 Answers9

5

Use:

Set<MyGenericType> keySet = map.keySet();

Always try to specify the Interface type for collections returned by these methods. This way regardless of the actual implementation class of the Set returned by these methods (in your case map.keySet()) you would be ok. This way if the next release the jdk guys use a different implementation for the returned Set your code will still work.

map.keySet() returns a View on the Keys of the map. Making changes to this view results in changing the underlying map though those changes are limited. See the javadoc for Map:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet%28%29

Yousuf Haider
  • 178
  • 2
  • 9
  • To reiterate what he said, if you now do keySet.remove(item), then 'item' will also disappear from 'map'. – SoloPilot Jan 26 '19 at 21:12
5
Map<String, String> someStrings = new HashMap<String, String>();
for(Map.Entry<String, String> entry : someStrings.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
}

This is how I like to iterate through Maps. If you specifically want just the keySet(), that answer is elsewhere on this page.

Droo
  • 3,177
  • 4
  • 22
  • 26
4
for ( String key : map.keySet() ) { 
 System.out.println( key );
}
lemon
  • 9,155
  • 7
  • 39
  • 47
0

Set t = map.ketSet()

The API does not specify what type of Set is returned.

You should try to declare variables as the interface rather than a particular implementation.

TofuBeer
  • 60,850
  • 18
  • 118
  • 163
0

Just

Set t = map.keySet();
bmargulies
  • 97,814
  • 39
  • 186
  • 310
0

Unless you're using an older JDK, I think its a little cleaner to use generics when using the Collections classes.

So thats

Set<MyType> s = map.keySet();

And then if you just iterate through them, then you can use any kind of loop you'd like. But if you're going to be modifying the map based on this keySet, you you have to use the keySet's iterator.

goatlinks
  • 761
  • 1
  • 4
  • 10
0

All that's guaranteed from keySet() is something that implements the interface Set. And that could possibly be some undocumented class like SecretHashSetKeys$foo, so just program to the interface Set.

I ran into this trying to get a view on a TreeSet, the return type ended up being TreeSet$3 on close examination.

Matt Stephenson
  • 8,442
  • 1
  • 19
  • 19
0
    Map<String, Object> map = new HashMap<>();
    map.put("name","jaemin");
    map.put("gender", "male");
    map.put("age", 30);
    Set<String> set = map.keySet();
    System.out.println("this is map : " + map);
    System.out.println("this is set : " + set);

It puts the key values in the map into the set.

jaemin
  • 39
  • 3
0

From Javadocs HashMap has several methods that can be used to manipulate and extract data from a hasmap.

public Set<K> keySet() Returns a Set view of the keys 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 the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations. Specified by: keySet in interface Map Overrides: keySet in class AbstractMap Returns: a set view of the keys contained in this map

so if you have a map myMap of any datatype , such that the map defined as map<T> , if you iterate it as follows:

for (T key : myMap.keySet() ) { 
     System.out.println(key); // which represent the value of datatype T
}

e.g if the map was defined as Map<Integer,Boolean>

Then for the above example we will have:

for (Integer key : myMap.keySet()){
  System.out.println(key) // the key printed out will be of type Integer
}
Amos Kosgei
  • 877
  • 8
  • 14