Using keySet () Method in HashMap

I have a method that goes through possible states on the board and saves 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 a group of keys. What to do to print them all?

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

LinkedHashSet t = map.keySet()
+5
source share
8 answers

Using:

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

Always try to specify the type of interface for collections returned by these methods. Thus, regardless of the actual implementation class of the set returned by these methods (in your case map.keySet ()), everything will be fine. Thus, if in the next release jdk guys use a different implementation for the returned code, your code will still work.

map.keySet() . , . . Javadoc :

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

+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();
}

. keySet(), .

+5
for ( String key : map.keySet() ) { 
 System.out.println( key );
}
+3

t = map.ketSet()

API .

, .

0

Set t = map.keySet();
0

JDK, , Collections.

,

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

, , , . , keySet.

0

All that is guaranteed from keySet()is what implements the interface Set. And it could be some kind of undocumented class like SecretHashSetKeys$foo, so just program the interface Set.

I came across this, trying to get an idea about TreeSet, the type of return ended up TreeSet$3with a closed exam.

0
source
    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 a set.

0
source

All Articles