Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the keySet() method in HashMap

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()
like image 239
andandandand Avatar asked Dec 11 '09 01:12

andandandand


3 Answers

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

like image 148
Yousuf Haider Avatar answered Oct 21 '22 03:10

Yousuf Haider


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.

like image 27
Droo Avatar answered Oct 21 '22 03:10

Droo


for ( String key : map.keySet() ) { 
 System.out.println( key );
}
like image 20
lemon Avatar answered Oct 21 '22 03:10

lemon