Java 使用 HashMap 中的 keySet() 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1885313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:33:40  来源:igfitidea点击:

Using the keySet() method in HashMap

javahashmaphashsetlinkedhashset

提问by andandandand

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

我有一种方法可以遍历电路板中的可能状态并将它们存储在 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

HashSet t = map.keySet()被编译器拒绝以及

LinkedHashSet t = map.keySet()

采纳答案by Yousuf Haider

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.

始终尝试为这些方法返回的集合指定接口类型。这样,无论这些方法返回的 Set 的实际实现类(在您的情况下是 map.keySet()),您都可以。这样,如果下一个版本的 jdk 人员对返回的 Set 使用不同的实现,您的代码仍然可以工作。

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:

map.keySet() 返回地图键上的视图。更改此视图会导致更改底层地图,但这些更改是有限的。请参阅 Map 的 javadoc:

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

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

回答by TofuBeer

Set t = map.ketSet()

设置 t = map.ketSet()

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

API 没有指定返回什么类型的 Set。

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

您应该尝试将变量声明为接口而不是特定的实现。

回答by bmargulies

Just

只是

Set t = map.keySet();

回答by goatlinks

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

除非您使用的是较旧的 JDK,否则我认为在使用 Collections 类时使用泛型会更简洁一些。

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.

然后如果你只是遍历它们,那么你可以使用任何你喜欢的循环。但是,如果您要根据此 keySet 修改映射,则必须使用 keySet 的迭代器。

回答by lemon

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

回答by Matt Stephenson

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.

所保证的keySet()只是实现 interface 的东西Set。这可能是一些未记录的类,例如SecretHashSetKeys$foo,只需对接口进行编程Set

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

我在试图查看 a 时遇到了这个问题TreeSet,最终对返回类型进行TreeSet$3了仔细检查。

回答by Droo

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.

这就是我喜欢遍历 Maps 的方式。如果您特别想要 keySet(),则该答案在本页的其他地方。

回答by jaemin

    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.

它将映射中的键值放入集合中。

回答by Amos Kosgei

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

从 JavadocsHashMap有几种方法可用于从 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

public Set<K> keySet()返回此映射中包含的键的 Set 视图。该集合由地图支持,因此对地图的更改会反映在该集合中,反之亦然。如果在对集合进行迭代时修改了映射(通过迭代器自己的删除操作除外),则迭代的结果是不确定的。该集合支持元素移除,通过 Iterator.remove、Set.remove、removeAll、retainAll 和 clear 操作从映射中移除相应的映射。它不支持 add 或 addAll 操作。指定者:接口 Map 中的 keySet 覆盖:类 AbstractMap 中的 keySet 返回:此映射中包含的键的集合视图

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

因此,如果您有任何数据类型的地图 myMap ,则该地图定义为map<T>,如果您按如下方式对其进行迭代:

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>

例如,如果地图被定义为 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
}