java - Java中HashMap的解析

标签 java parsing hashmap key

我有一个简单的问题。

我设置:

HashMap<A, B> myMap = new HashMap<A, B>();

...
myMap.put(...)
...

现在我想循环遍历 myMap 并获取所有键(A 类型)。我该怎么做?

我想通过循环从 myMap 获取所有键,并将它们发送到“void myFunction(A param){...}”。

最佳答案

这是基于问题标题的更通用的答案。

使用 entrySet() 解析键和值

HashMap<A, B> myMap = new HashMap<A, B>();

...
myMap.put(key, value);
...

for (Entry<A, B> e : myMap.entrySet()) {
    A key    = e.getKey();
    B value  = e.getValue();
}

//// or using an iterator:

// retrieve a set of the entries
Set<Entry<A, B>> entries = myMap.entrySet();
// parse the set
Iterator<Entry<A, B>> it = entries.iterator();
while(it.hasNext()) {
    Entry<A, B> e = it.next();
    A key   = e.getKey();
    B value = e.getValue();
}

使用keySet()解析键

HashMap<A, B> myMap = new HashMap<A, B>();

...
myMap.put(key, value);
...

for (A key   : myMap.keySet()) {
     B value = myMap.get(key);  //get() is less efficient 
}                               //than above e.getValue()

// for parsing using a Set.iterator see example above 

查看有关问题 Performance considerations for keySet() and entrySet() of MapentrySet()keySet() 的更多详细信息.

使用 values() 解析值

HashMap<A, B> myMap = new HashMap<A, B>();

...
myMap.put(key, value);
...

for (B value : myMap.values()) {
    ...
}

//// or using an iterator:

// retrieve a collection of the values (type B)
Collection<B> c = myMap.values();   
// parse the collection
Iterator<B> it = c.iterator();
while(it.hasNext())
  B value = it.next();
}

关于java - Java中HashMap的解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9129090/

相关文章:

java - 从 hashmap 的键对象中获取整数值

java.sql.SQLIntegrityConstraintViolationException : Column 'library_idlibrary' cannot be null

java - 从 Java Swing 应用程序拖放到 Windows 资源管理器

java - 为什么 hadoop 输出文件 part-r-00000 是空的

python - 从此 XML 文件中提取数据的最有效方法

python - 将 Bash 解析为 Python

java - 使用 Java 控制谷歌浏览器

regex - 使用 Perl 捕获输出,直到找到特定模式

java - 我可以对 hashmap (T) 中包含的数组列表进行排序吗?

Java,将键盘输入值与file.txt值进行比较