如何在 Java 中使用 foreach 循环来遍历 HashMap 中的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/448122/
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-11 14:45:23  来源:igfitidea点击:

How do I use a foreach loop in Java to loop through the values in a HashMap?

javaforeachhashmap

提问by troyal

I am trying to compile the following code:

我正在尝试编译以下代码:

private String dataToString(){
    Map data = (HashMap<MyClass.Key, String>) getData();
    String toString = "";
    for( MyClass.Key key: data.keySet() ){
        toString += key.toString() + ": " + data.get( key );
    return toString;
}

I get an error in the for line that says:

我在 for 行中收到一条错误消息:

incompatible types
found : java.lang.Object
required: MyClass.Key

The getData()method returns an Object(but in this case the Objectreturned has the HashMapstructure). MyClass.Keyis an enum that I have created for the purposes of my application (in another class file - MyClass).

getData()方法返回一个Object(但在这种情况下Object返回的具有HashMap结构)。 MyClass.Key是我为我的应用程序的目的而创建的枚举(在另一个类文件中 - MyClass)。

When I created a foreach loop with the same structure in MyClass.java, I did not encounter this problem.

当我在 中创建具有相同结构的 foreach 循环时MyClass.java,我没有遇到这个问题。

What am I doing wrong?

我究竟做错了什么?

采纳答案by Paul Tomblin

A slightly more efficient way to do this:

一个稍微更有效的方法来做到这一点:

  Map<MyClass.Key, String> data = (HashMap<MyClass.Key, String>) getData(); 
  StringBuffer sb = new StringBuffer();
  for (Map.Entry<MyClass.Key,String> entry : data.entrySet()) {
       sb.append(entry.getKey());
       sb.append(": ");
       sb.append(entry.getValue());
   }
   return sb.toString();

If at all possible, define "getData" so you don't need the cast.

如果可能,请定义“getData”,这样您就不需要演员表了。

回答by Craig P. Motlin

Change:

改变:

Map data = (HashMap<MyClass.Key, String>) getData();

to

Map<MyClass.Key, String> data = (HashMap<MyClass.Key, String>) getData();

The problem is that data.keySet()returns a Collection<Object>if data is just a Map. Once you make it generic, keySet()will return a Collection<MyClass.Key>. Even better... iterate over the entrySet(), which will be a Collection<MyClass.Key, String>. It avoids the extra hash lookups.

问题是data.keySet()返回一个Collection<Object>if 数据只是一个Map。一旦你使它通用,keySet()将返回一个Collection<MyClass.Key>. 更好的是......迭代entrySet(),这将是一个Collection<MyClass.Key, String>. 它避免了额外的哈希查找。

回答by Peter ?tibrany

Motlin's answer is correct.

莫特林的回答是正确的。

I have two notes...

我有两个笔记...

  1. Don't use toString += ..., but use StringBuilderinstead and append data to it.

  2. Cast which Martin suggested will give you unchecked warning, which you won't be able to get rid of, because it is really unsafe.

  1. 不要使用toString += ...,而是使用StringBuilder并将数据附加到它。

  2. 马丁建议的 Cast 会给你未经检查的警告,你将无法摆脱,因为它真的不安全。

Another way, without warning (and with StringBuilder):

另一种方式,没有警告(和 StringBuilder):

private String dataToString(){
    Map<?, ?> data = (Map<?, ?>) getData();
    StringBuilder toString = new StringBuilder();
    for (Object key: data.keySet()) {
        toString.append(key.toString());
        toString.append(": ");
        toString.append(data.get(key));
    }
    return toString.toString();
}

This works, because toString method which you call on keyis defined in Object class, so you don't need casting at all.

这是有效的,因为您调用的 toString 方法key是在 Object 类中定义的,所以您根本不需要强制转换。

Using entrySetis even better way, as it doesn't need to do another look-up in map.

使用entrySet是更好的方法,因为它不需要在地图中进行另一次查找。

回答by Richard Campbell

You could grab the entrySet instead, to avoid needing the key class:

您可以改为获取 entrySet,以避免需要 key 类:

private String dataToString(){    
    Map data = (HashMap<MyClass.Key, String>) getData();    
    String toString = "";    
    for( Map.Entry entry: data.entrySet() ) {        
        toString += entry.getKey() + ": " + entry.getValue();
    }    
    return toString;
}

回答by dialex

I found this simple example at java forum. Its syntax is very similar to the List's foreach, which was what I was looking for.

我在java 论坛上找到了这个简单的例子。它的语法与 List 的 foreach 非常相似,这正是我要找的。

import java.util.Map.Entry;
HashMap nameAndAges = new HashMap<String, Integer>();
for (Entry<String, Integer> entry : nameAndAges.entrySet()) {
        System.out.println("Name : " + entry.getKey() + " age " + entry.getValue());
}

[EDIT:] I tested it and it works perfectly.

[编辑:] 我测试了它,它完美地工作。