如果我有一个用Java实现Map接口的对象,并且我希望对其中包含的每一对进行迭代,那么最有效的方法是什么?
元素的顺序是否取决于我对接口的特定映射实现?
如果我有一个用Java实现Map接口的对象,并且我希望对其中包含的每一对进行迭代,那么最有效的方法是什么?
元素的顺序是否取决于我对接口的特定映射实现?
当前回答
在Map中,可以根据自己的兴趣对键和/或值和/或两者(例如entrySet)进行迭代,比如:
遍历贴图的keys->keySet():Map<String,Object>Map=。。。;for(字符串键:map.keySet()){//您的业务逻辑。。。}遍历映射的values->values():for(对象值:map.values()){//您的业务逻辑。。。}遍历映射的both->entrySet():for(Map.Entry<String,Object>Entry:Map.entrySet()){字符串键=entry.getKey();对象值=entry.getValue();//您的业务逻辑。。。}
此外,有3种不同的方法可以迭代HashMap。具体如下:
//1.
for (Map.Entry entry : hm.entrySet()) {
System.out.print("key,val: ");
System.out.println(entry.getKey() + "," + entry.getValue());
}
//2.
Iterator iter = hm.keySet().iterator();
while(iter.hasNext()) {
Integer key = (Integer)iter.next();
String val = (String)hm.get(key);
System.out.println("key,val: " + key + "," + val);
}
//3.
Iterator it = hm.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Integer key = (Integer)entry.getKey();
String val = (String)entry.getValue();
System.out.println("key,val: " + key + "," + val);
}
其他回答
如果要按元素添加的顺序遍历映射,请使用LinkedHashMap,而不是仅使用map。
这种方法在过去对我很有效:
LinkedHashMap<String,Integer> test=new LinkedHashMap();
test.put("foo",69);
test.put("bar",1337);
for(int i=0;i<test.size();i++){
System.out.println(test.get(test.keySet().toArray()[i]));
}
输出:
69
1337
Lambda表达式Java 8
在Java1.8(Java8)中,通过使用Aggregate操作(Stream操作)中的forEach方法,这变得更加容易,它看起来类似于Iterable接口中的迭代器。
只需将下面的粘贴语句复制到代码中,并将HashMap变量从hm重命名为HashMap变量,即可打印出键值对。
HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
/*
* Logic to put the Key,Value pair in your HashMap hm
*/
// Print the key value pair in one line.
hm.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));
// Just copy and paste above line to your code.
下面是我尝试使用Lambda表达式的示例代码。这东西太酷了。必须尝试。
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
Random rand = new Random(47);
int i = 0;
while(i < 5) {
i++;
int key = rand.nextInt(20);
int value = rand.nextInt(50);
System.out.println("Inserting key: " + key + " Value: " + value);
Integer imap = hm.put(key, value);
if( imap == null) {
System.out.println("Inserted");
} else {
System.out.println("Replaced with " + imap);
}
}
hm.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));
Output:
Inserting key: 18 Value: 5
Inserted
Inserting key: 13 Value: 11
Inserted
Inserting key: 1 Value: 29
Inserted
Inserting key: 8 Value: 0
Inserted
Inserting key: 2 Value: 7
Inserted
key: 1 value:29
key: 18 value:5
key: 2 value:7
key: 8 value:0
key: 13 value:11
同样也可以使用Spliterator。
Spliterator sit = hm.entrySet().spliterator();
更新
包括指向Oracle文档的文档链接。有关Lambda的更多信息,请访问此链接,必须阅读聚合操作,对于Spliterator,请访问该链接。
Java 8:
可以使用lambda表达式:
myMap.entrySet().stream().forEach((entry) -> {
Object currentKey = entry.getKey();
Object currentValue = entry.getValue();
});
有关详细信息,请遵循以下步骤。
这些都是迭代HashMap的所有可能方法。
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(1,"David"); //Adding elements in Map
map.put(2,"John");
map.put(4,"Samyuktha");
map.put(3,"jasmin");
System.out.println("Iterating Hashmap...");
//way 1 (java 8 Method)
map.forEach((key, value) -> {
System.out.println(key+" : "+ value);
});
//way 2 (java 7 Method)
for(Map.Entry me : map.entrySet()){
System.out.println(me.getKey()+" "+me.getValue());
}
//way 3 (Legacy way to iterate HashMap)
Iterator iterator = map.entrySet().iterator();//map.keySet().iterator()
while (iterator.hasNext())
{
Map.Entry me =(Map.Entry)iterator.next();
System.out.println(me.getKey()+" : "+ me.getValue());
}
}
我相信这是最简单的方法。。。
/* For example, this could be a map object */
Map<String, Integer> MAP = new Map<>();
// Do something like put keys/value pairs into the map, etc...
MAP.put("Denver", 35);
MAP.put("Patriots", 14);
/* Then, simply use a for each loop like this to iterate */
for (Object o : MAP.entrySet()) {
Map.Entry pair = (Map.Entry) o;
// Do whatever with the pair here (i.e. pair.getKey(), or pair.getValue();
}