# 如何有效地遍历Map中的每个条目？

` `Map<String, String> map = ... for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue()); }` `

1. 使用迭代器Map.Entry

` `long i = 0; Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Integer, Integer> pair = it.next(); i += pair.getKey() + pair.getValue(); }` `
2. 使用foreachMap.Entry

` `long i = 0; for (Map.Entry<Integer, Integer> pair : map.entrySet()) { i += pair.getKey() + pair.getValue(); }` `
3. `Java 8`使用forEach

` `final long[] i = {0}; map.forEach((k, v) -> i[0] += k + v);` `
4. 使用keySetforeach

` `long i = 0; for (Integer key : map.keySet()) { i += key + map.get(key); }` `
5. 使用keySet迭代器

` `long i = 0; Iterator<Integer> itr2 = map.keySet().iterator(); while (itr2.hasNext()) { Integer key = itr2.next(); i += key + map.get(key); }` `
6. 使用forMap.Entry

` `long i = 0; for (Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); entries.hasNext(); ) { Map.Entry<Integer, Integer> entry = entries.next(); i += entry.getKey() + entry.getValue(); }` `
7. 使用`Java 8` Stream Api

` `final long[] i = {0}; map.entrySet().stream().forEach(e -> i[0] += e.getKey() + e.getValue());` `
8. 使用`Java 8` Stream API并行

` `final long[] i = {0}; map.entrySet().stream().parallel().forEach(e -> i[0] += e.getKey() + e.getValue());` `
9. 使用`Apache Collections` IterableMap

` `long i = 0; MapIterator<Integer, Integer> it = iterableMap.mapIterator(); while (it.hasNext()) { i += it.next() + it.getValue(); }` `
10. 使用`Eclipse (CS) collections` MutableMap

` `final long[] i = {0}; mutableMap.forEachKeyValue((key, value) -> { i[0] += key + value; });` `

1）对于小地图（100个元素），得分0.308是最好的

` ` Benchmark Mode Cnt Score Error Units test3_UsingForEachAndJava8 avgt 10 0.308 ± 0.021 us/op test10_UsingEclipseMap avgt 10 0.309 ± 0.009 us/op test1_UsingWhileAndMapEntry avgt 10 0.380 ± 0.014 us/op test6_UsingForAndIterator avgt 10 0.387 ± 0.016 us/op test2_UsingForEachAndMapEntry avgt 10 0.391 ± 0.023 us/op test7_UsingJava8StreamApi avgt 10 0.510 ± 0.014 us/op test9_UsingApacheIterableMap avgt 10 0.524 ± 0.008 us/op test4_UsingKeySetAndForEach avgt 10 0.816 ± 0.026 us/op test5_UsingKeySetAndIterator avgt 10 0.863 ± 0.025 us/op test8_UsingJava8StreamApiParallel avgt 10 5.552 ± 0.185 us/op` `

2）对于有10000个元素的地图，得分37.606是最好的

` ` Benchmark Mode Cnt Score Error Units test10_UsingEclipseMap avgt 10 37.606 ± 0.790 us/op test3_UsingForEachAndJava8 avgt 10 50.368 ± 0.887 us/op test6_UsingForAndIterator avgt 10 50.332 ± 0.507 us/op test2_UsingForEachAndMapEntry avgt 10 51.406 ± 1.032 us/op test1_UsingWhileAndMapEntry avgt 10 52.538 ± 2.431 us/op test7_UsingJava8StreamApi avgt 10 54.464 ± 0.712 us/op test4_UsingKeySetAndForEach avgt 10 79.016 ± 25.345 us/op test5_UsingKeySetAndIterator avgt 10 91.105 ± 10.220 us/op test8_UsingJava8StreamApiParallel avgt 10 112.511 ± 0.365 us/op test9_UsingApacheIterableMap avgt 10 125.714 ± 1.935 us/op` `

3）对于10万个地图，1184.767是最好的

` ` Benchmark Mode Cnt Score Error Units test1_UsingWhileAndMapEntry avgt 10 1184.767 ± 332.968 us/op test10_UsingEclipseMap avgt 10 1191.735 ± 304.273 us/op test2_UsingForEachAndMapEntry avgt 10 1205.815 ± 366.043 us/op test6_UsingForAndIterator avgt 10 1206.873 ± 367.272 us/op test8_UsingJava8StreamApiParallel avgt 10 1485.895 ± 233.143 us/op test5_UsingKeySetAndIterator avgt 10 1540.281 ± 357.497 us/op test4_UsingKeySetAndForEach avgt 10 1593.342 ± 294.417 us/op test3_UsingForEachAndJava8 avgt 10 1666.296 ± 126.443 us/op test7_UsingJava8StreamApi avgt 10 1706.676 ± 436.867 us/op test9_UsingApacheIterableMap avgt 10 3289.866 ± 1445.564 us/op` `

` ` 100 600 1100 1600 2100 test10 0.333 1.631 2.752 5.937 8.024 test3 0.309 1.971 4.147 8.147 10.473 test6 0.372 2.19 4.47 8.322 10.531 test1 0.405 2.237 4.616 8.645 10.707 test2 0.376 2.267 4.809 8.403 10.91 test7 0.473 2.448 5.668 9.79 12.125 test9 0.565 2.83 5.952 13.22 16.965 test4 0.808 5.012 8.813 13.939 17.407 test5 0.81 5.104 8.533 14.064 17.422 test8 5.173 12.499 17.351 24.671 30.403` `

` ` Map<String,String> map = new HashMap<>(); map.put("SomeKey", "SomeValue"); map.forEach( (k,v) -> [do something with key and value] ); // such as map.forEach( (k,v) -> System.out.println("Key: " + k + ": Value: " + v));` `

`k``v`的types将由编译器推断，不再需要使用`Map.Entry`

@ ScArcher2拥有更优雅的Java 1.5语法。 在1.4中，我会做这样的事情：

` `Iterator entries = myMap.entrySet().iterator(); while (entries.hasNext()) { Entry thisEntry = (Entry) entries.next(); Object key = thisEntry.getKey(); Object value = thisEntry.getValue(); // ... }` `

` `Map<String,Thing> map = ...; for (Map.Entry<String,Thing> entry : map.entrySet()) { String key = entry.getKey(); Thing thing = entry.getValue(); ... }` `

`HashMap`是规范的映射实现，并没有做出保证（或者，如果没有变更操作，它不应该改变顺序）。 `SortedMap`将根据键的自然顺序或`Comparator` （如果提供）返回条目。 `LinkedHashMap`将按照插入顺序或访问顺序返回条目，具体取决于它是如何构build的。 `EnumMap`以键的自然顺序返回条目。

` `Iterator<Map.Entry<String, String>> entries = myMap.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); String key = entry.getKey(); String value = entry.getValue(); // ... }` `

`NavigableMap`是另一个有用的扩展 – 这是一个`SortedMap`带有额外的方法，用于通过它们在密钥集中的有序位置来查找条目。 因此，这可能会消除首先迭代的需要 – 在使用`higherEntry``lowerEntry``ceilingEntry``floorEntry`方法之后，您可能能够find特定`entry``descendingMap`方法甚至给你一个反转遍历顺序的显式方法。

1）在每个循环中使用`entrySet()`

` `for (Map.Entry<String,Integer> entry : testMap.entrySet()) { entry.getKey(); entry.getValue(); }` `

50毫秒

2）在每个循环中使用`keySet()`

` `for (String key : testMap.keySet()) { testMap.get(key); }` `

76毫秒

3）使用`entrySet()`和迭代器

` `Iterator<Map.Entry<String,Integer>> itr1 = testMap.entrySet().iterator(); while(itr1.hasNext()) { Map.Entry<String,Integer> entry = itr1.next(); entry.getKey(); entry.getValue(); }` `

50毫秒

4）使用`keySet()`和迭代器

` `Iterator itr2 = testMap.keySet().iterator(); while(itr2.hasNext()) { String key = itr2.next(); testMap.get(key); }` `

75毫秒

` `for (String key: map.keySet()) { System.out.println(key + "/" + map.get(key)); }` `

` `final MutableBag<String> result = Bags.mutable.empty(); MutableMap<Integer, String> map = Maps.mutable.of(1, "One", 2, "Two", 3, "Three"); map.forEachKeyValue(new Procedure2<Integer, String>() { public void value(Integer key, String value) { result.add(key + value); } }); Assert.assertEquals(Bags.mutable.of("1One", "2Two", "3Three"), result);` `

` `MutableBag<String> result = Bags.mutable.empty(); MutableMap<Integer, String> map = Maps.mutable.of(1, "One", 2, "Two", 3, "Three"); map.forEachKeyValue((key, value) -> { result.add(key + value);}); Assert.assertEquals(Bags.mutable.of("1One", "2Two", "3Three"), result);` `

` `for( Iterator entries = myMap.entrySet().iterator(); entries.hasNext();){ Entry entry = (Entry) entries.next(); System.out.println(entry.getKey() + "/" + entry.getValue()); //... }` `

JAVA 8

` `myMap.entrySet().stream().forEach((entry) -> { Object currentKey = entry.getKey(); Object currentValue = entry.getValue(); });` `

1.）遍历映射的`keys -> keySet()`

` `Map<String, Object> map = ...; for (String key : map.keySet()) { //your Business logic... }` `

2.）迭代通过`values -> values()`的地图：

` `for (Object value : map.values()) { //your Business logic... }` `

3.）迭代映射的`both -> entrySet()`

` `for (Map.Entry<String, Object> entry : map.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); //your Business logic... }` `

` `//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); }` `

` `public class abcd{ public static void main(String[] args) { Map<Integer, String> testMap = new HashMap<Integer, String>(); testMap.put(10, "a"); testMap.put(20, "b"); testMap.put(30, "c"); testMap.put(40, "d"); for (Integer key:testMap.keySet()) { String value=testMap.get(key); System.out.println(value); } } }` `

` `public class abcd { public static void main(String[] args) { Map<Integer, String> testMap = new HashMap<Integer, String>(); testMap.put(10, "a"); testMap.put(20, "b"); testMap.put(30, "c"); testMap.put(40, "d"); for (Entry<Integer, String> entry : testMap.entrySet()) { Integer key=entry.getKey(); String value=entry.getValue(); } } }` `

Lambda Expression Java 8

` `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.` `

` `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 sit = hm.entrySet().spliterator();` `

UPDATE

` `Map map = new HashMap(); for (Map.Entry entry : ((Set<Map.Entry>) map.entrySet())) { System.out.println(entry.getKey() + "/" + entry.getValue()); }` `
` ` Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry element = (Map.Entry)it.next(); LOGGER.debug("Key: " + element.getKey()); LOGGER.debug("value: " + element.getValue()); }` `

` `Map<Integer, Integer> map = new HashMap<Integer, Integer>(); Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<Integer, Integer> entry = entries.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }` `

` ` | | - - - - | | for (Map.Entry<String, Object> entry : map.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); }` `
` `Iterator itr2 = testMap.keySet().iterator(); while (itr2.hasNext()) { String key = itr2.next(); testMap.get(key); } for (String key: map.keySet()) { System.out.println(key + "/" + map.get(key)); }` `

` ` //Functional Oprations Map<String, String> mapString = new HashMap<>(); mapString.entrySet().stream().map((entry) -> { String mapKey = entry.getKey(); return entry; }).forEach((entry) -> { String mapValue = entry.getValue(); }); //Intrator Map<String, String> mapString = new HashMap<>(); for (Iterator<Map.Entry<String, String>> it = mapString.entrySet().iterator(); it.hasNext();) { Map.Entry<String, String> entry = it.next(); String mapKey = entry.getKey(); String mapValue = entry.getValue(); } //Simple for loop Map<String, String> mapString = new HashMap<>(); for (Map.Entry<String, String> entry : mapString.entrySet()) { String mapKey = entry.getKey(); String mapValue = entry.getValue(); }` `

` `Map<String,String> sample = new HashMap<>(); sample.put("A","Apple"); sample.put("B", "Ball");` `

` `sample.keySet().forEach((k) -> System.out.println(k));` `

` `sample.values().forEach((v) -> System.out.println(v));` `

` `sample.forEach((k,v) -> System.out.println(k + "=" + v)); sample.entrySet().stream().forEach((entry) -> { Object currentKey = entry.getKey(); Object currentValue = entry.getValue(); System.out.println(currentKey + "=" + currentValue); });` `

stream的好处是可以很容易地并行，以防万一。 我们只需要使用`parallelStream()`代替上面的`stream()`

` `package com.test; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class Test { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("ram", "ayodhya"); map.put("krishan", "mathura"); map.put("shiv", "kailash"); System.out.println("********* Keys *********"); Set<String> keys = map.keySet(); for (String key : keys) { System.out.println(key); } System.out.println("********* Values *********"); Collection<String> values = map.values(); for (String value : values) { System.out.println(value); } System.out.println("***** Keys and Values (Using for each loop) *****"); for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("Key: " + entry.getKey() + "\t Value: " + entry.getValue()); } System.out.println("***** Keys and Values (Using while loop) *****"); Iterator<Entry<String, String>> entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = (Map.Entry<String, String>) entries .next(); System.out.println("Key: " + entry.getKey() + "\t Value: " + entry.getValue()); } System.out .println("** Keys and Values (Using java 8 using lambdas )***"); map.forEach((k, v) -> System.out .println("Key: " + k + "\t value: " + v)); } }` `

` `Map<Ktype, Vtype> myMap = [...]; for (Vtype v: myMap.values()) { System.out.println("value: " + v); }` `

`Ktype``Vtype`是伪代码。

` `import java.util.Iterator; import java.util.Map; public class MapUtils { static interface ItemCallback<K, V> { void handler(K key, V value, Map<K, V> map); } public static <K, V> void forEach(Map<K, V> map, ItemCallback<K, V> callback) { Iterator<Map.Entry<K, V>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<K, V> entry = it.next(); callback.handler(entry.getKey(), entry.getValue(), map); } } public static <K, V> void printMap(Map<K, V> map) { forEach(map, new ItemCallback<K, V>() { @Override public void handler(K key, V value, Map<K, V> map) { System.out.println(key + " = " + value); } }); } }` `

## 例

` `import java.util.*; public class MapPrinter { public static void main(String[] args) { List<Map<?, ?>> maps = new ArrayList<Map<?, ?>>() { private static final long serialVersionUID = 1L; { add(new LinkedHashMap<String, Integer>() { private static final long serialVersionUID = 1L; { put("One", 0); put("Two", 1); put("Three", 3); } }); add(new LinkedHashMap<String, Object>() { private static final long serialVersionUID = 1L; { put("Object", new Object()); put("Integer", new Integer(0)); put("Double", new Double(0.0)); } }); } }; for (Map<?, ?> map : maps) { MapUtils.printMap(map); System.out.println(); } } }` `

## 产量

` `One = 0 Two = 1 Three = 3 Object = java.lang.Object@15db9742 Integer = 0 Double = 0.0` `

` `import com.google.common.collect.Maps;` `

`Maps`添加到导入之后，可以在地图上使用`Maps.transformValues``Maps.transformEntries` ，如下所示：

` `public void transformMap(){ Map<String, Integer> map = new HashMap<>(); map.put("a", 2); map.put("b", 4); Map<String, Integer> result = Maps.transformValues(map, num -> num * 2); result.forEach((key, val) -> print(key, Integer.toString(val))); // key=a,value=4 // key=b,value=8 Map<String, String> result2 = Maps.transformEntries(map, (key, value) -> value + "[" + key + "]"); result2.forEach(this::print); // key=a,value=2[a] // key=b,value=4[b] } private void print(String key, String val){ System.out.println("key=" + key + ",value=" + val); }` `

sorting总是取决于具体的地图实现。 使用Java8，你可以使用下面的任何一个：

` `map.forEach((k,v) -> { System.out.println(k + ":" + v); });` `

` `map.entrySet().forEach((e) -> { System.out.println(e.getKey() + " : " + e.getValue()); });` `

` `map.entrySet() .stream() .filter(e-> e.getValue() > 5) .forEach(System.out::println);` `

` `public class HMIteration { public static void main(String[] args) { Map<Object, Object> linkedHashMap = new LinkedHashMap<>(); Map<Object, Object> hashMap = new HashMap<>(); for (int i=10; i>=0; i--) { linkedHashMap.put(i, i); hashMap.put(i, i); } System.out.println("LinkedHashMap (1): "); linkedHashMap.forEach((k,v) -> { System.out.print(k + " (#="+k.hashCode()+"):" + v + ", "); }); System.out.println("\nLinkedHashMap (2): "); linkedHashMap.entrySet().forEach((e) -> { System.out.print(e.getKey() + " : " + e.getValue() + ", "); }); System.out.println("\n\nHashMap (1): "); hashMap.forEach((k,v) -> { System.out.print(k + " (#:"+k.hashCode()+"):" + v + ", "); }); System.out.println("\nHashMap (2): "); hashMap.entrySet().forEach((e) -> { System.out.print(e.getKey() + " : " + e.getValue() + ", "); }); } }` `

10（＃= 10）：10,9（＃= 9）：9,8（＃= 8）：8,7（＃= 7）：7,6（＃= 6） ）：5，4（＃= 4）:4,3（＃= 3）:3,2（＃= 2）：2,1（＃= 1）：1,0（＃= 0）

10：10,9：9,8：8,7：7,6：6,5：5，4：4，3：3，2：2，1：1,0：

HashMap（1）：

0（＃：0）：0,1（#:1）：1,2（#:2）：2,3（#:3）:3,4（#:4）：4,5（＃ ）：5,6（#:6）：6,7（#:7）：7,8（#:8）：8,9（#:9）：9,10（#:10）

HashMap（2）：

0：0,1：1,2：2,3：3,4：4,5：5,6：6,7：7,8：8,9：9,10：10,1：

There are the several way to iterate a map please refer the following code When you iterate a map using iterator Interface you must to go with Entry or entrySet() look like this

` `import java.util.*; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class IteratMapDemo{ public static void main(String arg[]){ Map<String,String> mapOne =new HashMap<String,String>(); mapOne.put("1","January"); mapOne.put("2","February"); mapOne.put("3","March"); mapOne.put("4","April"); mapOne.put("5","May"); mapOne.put("6","June"); mapOne.put("7","July"); mapOne.put("8","August"); mapOne.put("9","September"); mapOne.put("10","Octomber"); mapOne.put("11","November"); mapOne.put("12","December"); Iterator it = mapOne.entrySet().iterator(); while(it.hasNext()) { Map.Entry me=(Map.Entry) it.next(); //System.out.println("Get Key through While loop = " +me.getKey()); } for(Map.Entry<String,String> entry:mapOne.entrySet()){ //System.out.println(entry.getKey() + "=" +entry.getValue() ); } for (Object key : mapOne.keySet()) { System.out.println("Key : " + key.toString() + " Value : " + mapOne.get(key)); } } }` `