如何有效地迭代“Map”中的每个条目?

时间:2021-02-17 14:32:50

If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?

如果我有一个在Java中实现Map接口的对象,并且我希望遍历其中包含的每一对,那么遍历Map的最有效方法是什么?

Will the ordering of elements depend on the specific map implementation that I have for the interface?

元素的顺序是否取决于我为接口提供的特定映射实现?

38 个解决方案

#1


4025  

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

#2


639  

To summarize the other answers and combine them with what I know, I found 10 main ways to do this (see below). Also, I wrote some performance tests (see results below). For example, if we want to find the sum of all of the keys and values of a map, we can write:

为了总结其他答案并将它们与我所知道的结合起来,我找到了10种主要的方法。此外,我还编写了一些性能测试(参见下面的结果)。例如,如果我们想找到一个地图的所有键和值的总和,我们可以这样写:

  1. Using iterator and Map.Entry

    使用迭代器和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. Using foreach and Map.Entry

    使用foreach和map . entry

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

    使用来自Java 8的forEach

    final long[] i = {0};
    map.forEach((k, v) -> i[0] += k + v);
    
  4. Using keySet and foreach

    使用键盘和foreach

    long i = 0;
    for (Integer key : map.keySet()) {
        i += key + map.get(key);
    }
    
  5. Using keySet and iterator

    使用键盘和迭代器

    long i = 0;
    Iterator<Integer> itr2 = map.keySet().iterator();
    while (itr2.hasNext()) {
        Integer key = itr2.next();
        i += key + map.get(key);
    }
    
  6. Using for and Map.Entry

    使用和map . 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. Using the Java 8 Stream API

    使用Java 8流API

    final long[] i = {0};
    map.entrySet().stream().forEach(e -> i[0] += e.getKey() + e.getValue());
    
  8. Using the Java 8 Stream API parallel

    使用Java 8流API并行

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

    使用Apache集合的IterableMap

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

    使用Eclipse (CS)集合的MutableMap

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

Perfomance tests (mode = AverageTime, system = Windows 8.1 64-bit, Intel i7-4790 3.60 GHz, 16 GB)

性能测试(mode = AverageTime, system = Windows 8.1 64位,Intel i7- 47903.60 GHz, 16gb)

  1. For small map (100 elements), score 0.308 is the best

    对于小地图(100个元素),得分0.308为最佳

    Benchmark                          Mode  Cnt  Score    Error  Units
    test3_UsingForEachAndJava8         avgt  10   0.308 ±  0.021  µs/op
    test10_UsingEclipseMap             avgt  10   0.309 ±  0.009  µs/op
    test1_UsingWhileAndMapEntry        avgt  10   0.380 ±  0.014  µs/op
    test6_UsingForAndIterator          avgt  10   0.387 ±  0.016  µs/op
    test2_UsingForEachAndMapEntry      avgt  10   0.391 ±  0.023  µs/op
    test7_UsingJava8StreamApi          avgt  10   0.510 ±  0.014  µs/op
    test9_UsingApacheIterableMap       avgt  10   0.524 ±  0.008  µs/op
    test4_UsingKeySetAndForEach        avgt  10   0.816 ±  0.026  µs/op
    test5_UsingKeySetAndIterator       avgt  10   0.863 ±  0.025  µs/op
    test8_UsingJava8StreamApiParallel  avgt  10   5.552 ±  0.185  µs/op
    
  2. For map with 10000 elements, score 37.606 is the best

    对于包含10000个元素的地图,得分37.606是最好的

    Benchmark                           Mode   Cnt  Score      Error   Units
    test10_UsingEclipseMap              avgt   10    37.606 ±   0.790  µs/op
    test3_UsingForEachAndJava8          avgt   10    50.368 ±   0.887  µs/op
    test6_UsingForAndIterator           avgt   10    50.332 ±   0.507  µs/op
    test2_UsingForEachAndMapEntry       avgt   10    51.406 ±   1.032  µs/op
    test1_UsingWhileAndMapEntry         avgt   10    52.538 ±   2.431  µs/op
    test7_UsingJava8StreamApi           avgt   10    54.464 ±   0.712  µs/op
    test4_UsingKeySetAndForEach         avgt   10    79.016 ±  25.345  µs/op
    test5_UsingKeySetAndIterator        avgt   10    91.105 ±  10.220  µs/op
    test8_UsingJava8StreamApiParallel   avgt   10   112.511 ±   0.365  µs/op
    test9_UsingApacheIterableMap        avgt   10   125.714 ±   1.935  µs/op
    
  3. For map with 100000 elements, score 1184.767 is the best

    对于包含100000个元素的地图,得分1184.767是最好的

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

Graphs (perfomance tests depending on map size)

图(基于地图大小的性能测试)

如何有效地迭代“Map”中的每个条目?

Table (perfomance tests depending on map size)

表(基于地图大小的性能测试)

          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.190    4.470    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.910
test7     0.473    2.448    5.668    9.790   12.125
test9     0.565    2.830    5.952   13.220   16.965
test4     0.808    5.012    8.813   13.939   17.407
test5     0.810    5.104    8.533   14.064   17.422
test8     5.173   12.499   17.351   24.671   30.403

All tests are on GitHub.

所有的测试都在GitHub上。

#3


219  

In Java 8 you can do it clean and fast using the new lambdas features:

在Java 8中,您可以使用新的lambdas特性来快速地完成它:

 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));

The type of k and v will be inferred by the compiler and there is no need to use Map.Entry anymore.

编译器将推断k和v的类型,不需要使用Map。条目了。

Easy-peasy!

非常简单!

#4


192  

Yes, the order depends on the specific Map implementation.

是的,顺序取决于特定的映射实现。

@ScArcher2 has the more elegant Java 1.5 syntax. In 1.4, I would do something like this:

@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();
  // ...
}

#5


98  

Typical code for iterating over a map is:

在地图上迭代的典型代码是:

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

HashMap is the canonical map implementation and doesn't make guarantees (or though it should not change order if no mutating operation are performed on it). SortedMap will return entries based on the natural ordering of the keys, or a Comparator, if provided. LinkedHashMap will either return entries in insertion-order or access-order depending upon how it has been constructed. EnumMap returns entries in natural order of keys.

HashMap是规范的map实现,并没有做出保证(或者,如果在它上没有进行突变操作,它不应该改变顺序)。SortedMap将根据键的自然顺序返回条目,如果提供的话,还将返回一个比较器。LinkedHashMap要么以插入顺序返回条目,要么以访问顺序返回条目,这取决于它是如何构造的。EnumMap以自然顺序的键返回条目。

(Update: I think this is no longer true.) Note, IdentityHashMap entrySet iterator currently has a peculiar implementation which returns the same Map.Entry instance for every item in the entrySet! However, every time a new the iterator advances the Map.Entry is updated.

(更新:我认为这已经不是真的了。)注意,IdentityHashMap entrySet迭代器当前有一个特殊的实现,它返回相同的映射。每个条目的入口实例!但是,每当一个新的迭代器推进映射时。条目更新。

#6


87  

Example of using iterator and generics:

使用迭代器和泛型的示例:

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

#7


76  

This is a two part question:

这是一个由两部分组成的问题:

How to iterate over the entries of a Map - @ScArcher2 has answered that perfectly.

如何遍历Map - @ScArcher2的条目已经很好地回答了这个问题。

What is the order of iteration - if you are just using Map, then strictly speaking, there are no ordering guarantees. So you shouldn't really rely on the ordering given by any implementation. However, the SortedMap interface extends Map and provides exactly what you are looking for - implementations will aways give a consistent sort order.

迭代的顺序是什么?如果您只是使用Map,那么严格地说,没有排序保证。所以你不应该依赖于任何实现给出的顺序。然而,SortedMap接口扩展了Map并提供了您所需要的东西——实现总是给出一致的排序顺序。

NavigableMap is another useful extension - this is a SortedMap with additional methods for finding entries by their ordered position in the key set. So potentially this can remove the need for iterating in the first place - you might be able to find the specific entry you are after using the higherEntry, lowerEntry, ceilingEntry, or floorEntry methods. The descendingMap method even gives you an explicit method of reversing the traversal order.

NavigableMap是——这是另一个有用的扩展与额外的方法寻找SortedMap下令在关键位置设置条目。这可能可以删除需要迭代的——你可能会发现使用higherEntry后的具体条目,lowerEntry ceilingEntry或floorEntry方法。下行映射方法甚至为您提供了一个反转遍历顺序的显式方法。

#8


62  

There are several ways to iterate over map.

有几种方法可以迭代映射。

Here is comparison of their performances for a common data set stored in map by storing a million key value pairs in map and will iterate over map.

下面是它们对存储在map中的公共数据集的性能的比较,通过在map中存储一百万对键值对并在map上迭代。

1) Using entrySet() in for each loop

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

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

50 milliseconds

50毫秒

2) Using keySet() in for each loop

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

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

76 milliseconds

76毫秒

3) Using entrySet() and iterator

3)使用entrySet()和iterator

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

50 milliseconds

50毫秒

4) Using keySet() and iterator

4)使用keySet()和iterator

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

75 milliseconds

75毫秒

I have referred this link.

我已经提到了这个链接。

#9


41  

FYI, you can also use map.keySet() and map.values() if you're only interested in keys/values of the map and not the other.

顺便说一下,如果您只对map. keyset()和map.values()感兴趣,那么也可以使用map. keyset()和map.values()。

#10


40  

The correct way to do this is to use the accepted answer as it is the most efficient. I find the following code looks a bit cleaner.

正确的做法是使用公认的答案,因为它是最有效的。我发现下面的代码看起来更简洁一些。

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

#11


21  

With Eclipse Collections (formerly GS Collections), you would use the forEachKeyValue method on the MapIterable interface, which is inherited by the MutableMap and ImmutableMap interfaces and their implementations.

使用Eclipse集合(以前是GS集合),您将在MapIterable接口上使用forEachKeyValue方法,它由MutableMap和ImmutableMap接口及其实现继承。

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);

With Java 8 lambda syntax, you can write the code as follows:

使用Java 8 lambda语法,可以编写如下代码:

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);

Note: I am a committer for Eclipse Collections.

注意:我是Eclipse集合的提交者。

#12


19  

Try this with Java 1.4:

用Java 1.4试试这个:

for( Iterator entries = myMap.entrySet().iterator(); entries.hasNext();){

  Entry entry = (Entry) entries.next();

  System.out.println(entry.getKey() + "/" + entry.getValue());

  //...
}

#13


18  

Java 8:

Java 8:

You can use lambda expressions:

你可以使用lambda表达式:

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

For more information, follow this.

要了解更多信息,请遵循以下步骤。

#14


17  

In theory, the most efficient way will depend on which implementation of Map. The official way to do this is to call map.entrySet(), which returns a set of Map.Entry, each of which contains a key and a value (entry.getKey() and entry.getValue()).

理论上,最有效的方法将取决于映射的实现。正式的方法是调用Map. entryset(),它返回一组映射。条目,每个条目都包含一个键和一个值(entr. getkey()和entr. getvalue())。

In an idiosyncratic implementation, it might make some difference whether you use map.keySet(), map.entrySet() or something else. But I can't think of a reason why anyone would write it like that. Most likely it makes no difference to performance what you do.

在特殊的实现中,使用map.keySet()、map.entrySet()或其他东西可能会有所不同。但是我想不出为什么有人会这样写。很可能你所做的对表现没有影响。

And yes, the order will depend on the implementation - as well as (possibly) the order of insertion and other hard-to-control factors.

是的,顺序将取决于实现,以及(可能的)插入顺序和其他难以控制的因素。

[edit] I wrote valueSet() originally but of course entrySet() is actually the answer.

[编辑]我最初编写了valueSet(),但当然entrySet()实际上就是答案。

#15


15  

In Map one can Iteration over keys and/or values and/or both (e.g., entrySet) depends on one's interested in_ Like:

在Map中,一个人可以迭代键和/或值以及/或两者(例如,entrySet),这取决于他的兴趣所在:

1.) Iterate through the keys -> keySet() of the map:

1)。遍历map的key -> keySet():

Map<String, Object> map = ...;

for (String key : map.keySet()) {
    //your Business logic...
}

2.) Iterate through the values -> values() of the map:

2)。遍历映射的值->值():

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

3.) Iterate through the both -> entrySet() of the map:

3)。遍历map的-> entrySet():

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

Moreover, there are 3 difference ways to Iterate Through a HashMap. They are as below_

此外,有三种不同的方法可以遍历HashMap。他们是below_

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

#16


15  

Lambda Expression Java 8

Lambda表达式Java 8

In Java 1.8 (Java 8) this has become lot easier by using forEach method from Aggregate operations(Stream operations) that looks similar to iterators from Iterable Interface.

在Java 1.8 (Java 8)中,通过使用聚合操作(流操作)中的forEach方法,这变得容易得多,这种方法看起来类似于迭代接口中的迭代器。

Just copy paste below statement to your code and rename the HashMap variable from hm to your HashMap variable to print out key-value pair.

只需将下面的语句复制到代码中,并将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.

Below is the sample code that i tried using Lambda Expression. This stuff is so cool. Must try.

下面是我尝试使用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

Also one can use Spliterator for the same.

同样也可以使用Spliterator。

Spliterator sit = hm.entrySet().spliterator();

UPDATE

更新


Including documentation links to Oracle Docs. For more on Lambda go to this link and must read Aggregate Operations and for Spliterator go to this link.

包括文档链接到Oracle文档。有关Lambda的更多信息,请转到该链接,并必须读取聚合操作,Spliterator转到该链接。

#17


14  

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

OR

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();
        }
    }
}

#18


12  

If you have a generic untyped Map you can use:

如果你有一个通用的非类型化地图,你可以使用:

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

#19


8  

    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());    
    }

#20


7  

You can do it using generics:

你可以使用泛型:

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());
}

#21


6  

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

The best way is entrySet() though.

最好的方法是entrySet()。

#22


5  

           //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();

            }

#23


5  

Yes, as many people agreed this is the best way to iterate over a Map.

是的,很多人都认为这是迭代地图的最佳方式。

But there are chances to throw nullpointerexception if the map is null. Don't forget to put null .check in.

但是如果映射是空的,则有可能抛出nullpointerexception。不要忘记输入null。check in。

                                                 |
                                                 |
                                         - - - -
                                       |
                                       |
for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
}

#24


4  

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

#25


3  

If your reason for iterating trough the Map, is to do an operation on the value and write to a resulting Map. I recommend using the transform-methods in the Google Guava Maps class.

如果您迭代映射的原因是对值执行操作并写入结果映射。我建议在谷歌番石榴映射类中使用转换方法。

import com.google.common.collect.Maps;

After you have added the Maps to your imports, you can use Maps.transformValues and Maps.transformEntries on your maps, like this:

将映射添加到导入之后,就可以使用映射了。transformValues和地图。变换地图上的条目,比如:

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

#26


3  

In Java 8 we have got forEach method that accepts a lambda expression. We have also got stream APIs. Consider a map:

在Java 8中,我们有forEach方法,它接受lambda表达式。我们也有流api。考虑一个地图:

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

Iterate over keys:

遍历键:

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

Iterate over values:

遍历值:

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

Iterate over entries (Using forEach and Streams):

迭代条目(使用forEach和Streams):

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

The advantage with streams is they can be parallelized easily in case we want to. We simply need to use parallelStream() in place of stream() above.

流的优点是它们可以很容易地并行化,以备我们需要。我们只需要在上面的stream()中使用parallelStream()。

#27


3  

There are a lot of ways to do this. Below is a few simple steps:

有很多方法可以做到这一点。下面是一些简单的步骤:

Suppose you have one Map like:

假设你有一张这样的地图:

Map<String, Integer> m = new HashMap<String, Integer>();

Then you can do something like the below to iterate over map elements.

然后您可以执行如下操作来遍历映射元素。

// ********** Using an iterator ****************
Iterator<Entry<String, Integer>> me = m.entrySet().iterator();
while(me.hasNext()){
    Entry<String, Integer> pair = me.next();
    System.out.println(pair.getKey() + ":" + pair.getValue());
}

// *********** Using foreach ************************
for(Entry<String, Integer> me : m.entrySet()){
    System.out.println(me.getKey() + " : " + me.getValue());
}

// *********** Using keySet *****************************
for(String s : m.keySet()){
    System.out.println(s + " : " + m.get(s));
}

// *********** Using keySet and iterator *****************
Iterator<String> me = m.keySet().iterator();
while(me.hasNext()){
    String key = me.next();
    System.out.println(key + " : " + m.get(key));
}

#28


2  

It doesn't quite answer the OP's question, but might be useful to others who find this page:

它并没有很好地回答OP的问题,但是可能对发现这个页面的其他人有用:

If you only need the values and not the keys, you can do this:

如果你只需要值而不需要键,你可以这样做:

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

Ktype, Vtype are pseudocode.

Ktype,Vtype伪代码。

#29


2  

Here is a generic type-safe method which can be called to dump any given Map.

这里有一个通用的类型安全方法,可以调用它来转储任何给定的映射。

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

Example

Here is an example of its use. Notice that the type of the Map is inferred by the method.

这里有一个使用它的例子。注意,映射的类型是由方法推断的。

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();
        }
    }
}

Output

One = 0
Two = 1
Three = 3

Object = java.lang.Object@15db9742
Integer = 0
Double = 0.0

#30


2  

The ordering will always depend on the specific map implementation. Using Java 8 you can use either of these:

排序始终取决于特定的映射实现。使用Java 8,您可以使用以下任何一种:

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

Or:

或者:

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

The result will be the same (same order). The entrySet backed by the map so you are getting the same order. The second one is handy as it allows you to use lambdas, e.g. if you want only to print only Integer objects that are greater than 5:

结果是相同的(顺序相同)。由映射支持的入口集,因此您将得到相同的顺序。第二种方法很方便,因为它允许您使用lambdas,例如,如果您只想打印大于5的整数对象:

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

The code below shows iteration through LinkedHashMap and normal HashMap (example). You will see difference in the order:

下面的代码通过LinkedHashMap和normal HashMap(示例)显示了迭代。您将看到顺序上的差异:

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() + ", ");
        });
    }
}

LinkedHashMap (1):

LinkedHashMap(1):

10 (#=10):10, 9 (#=9):9, 8 (#=8):8, 7 (#=7):7, 6 (#=6):6, 5 (#=5):5, 4 (#=4):4, 3 (#=3):3, 2 (#=2):2, 1 (#=1):1, 0 (#=0):0,

10(# = 10):9(# = 9):9,8(# = 8):8、7(# = 7):7,6(# = 6):6,5(# = 5):5、4(# = 4):4 3(# = 3):3,2(# = 2):2、1(# = - 1):1,0(# = 0):0,

LinkedHashMap (2):

LinkedHashMap(2):

10 : 10, 9 : 9, 8 : 8, 7 : 7, 6 : 6, 5 : 5, 4 : 4, 3 : 3, 2 : 2, 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: 0,

HashMap (1):

HashMap(1):

0 (#:0):0, 1 (#:1):1, 2 (#:2):2, 3 (#:3):3, 4 (#:4):4, 5 (#:5):5, 6 (#:6):6, 7 (#:7):7, 8 (#:8):8, 9 (#:9):9, 10 (#:10):10,

0(#:0):0、1(#:1):1、2(#:2):2、3(#:3):3、4(#:4):4、5(#:5):5、6(#:6):6、7(#:7):7、8(#:8):8、9(#:9):9,10(#:10):10

HashMap (2):

HashMap(2):

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

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

#1


4025  

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

#2


639  

To summarize the other answers and combine them with what I know, I found 10 main ways to do this (see below). Also, I wrote some performance tests (see results below). For example, if we want to find the sum of all of the keys and values of a map, we can write:

为了总结其他答案并将它们与我所知道的结合起来,我找到了10种主要的方法。此外,我还编写了一些性能测试(参见下面的结果)。例如,如果我们想找到一个地图的所有键和值的总和,我们可以这样写:

  1. Using iterator and Map.Entry

    使用迭代器和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. Using foreach and Map.Entry

    使用foreach和map . entry

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

    使用来自Java 8的forEach

    final long[] i = {0};
    map.forEach((k, v) -> i[0] += k + v);
    
  4. Using keySet and foreach

    使用键盘和foreach

    long i = 0;
    for (Integer key : map.keySet()) {
        i += key + map.get(key);
    }
    
  5. Using keySet and iterator

    使用键盘和迭代器

    long i = 0;
    Iterator<Integer> itr2 = map.keySet().iterator();
    while (itr2.hasNext()) {
        Integer key = itr2.next();
        i += key + map.get(key);
    }
    
  6. Using for and Map.Entry

    使用和map . 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. Using the Java 8 Stream API

    使用Java 8流API

    final long[] i = {0};
    map.entrySet().stream().forEach(e -> i[0] += e.getKey() + e.getValue());
    
  8. Using the Java 8 Stream API parallel

    使用Java 8流API并行

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

    使用Apache集合的IterableMap

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

    使用Eclipse (CS)集合的MutableMap

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

Perfomance tests (mode = AverageTime, system = Windows 8.1 64-bit, Intel i7-4790 3.60 GHz, 16 GB)

性能测试(mode = AverageTime, system = Windows 8.1 64位,Intel i7- 47903.60 GHz, 16gb)

  1. For small map (100 elements), score 0.308 is the best

    对于小地图(100个元素),得分0.308为最佳

    Benchmark                          Mode  Cnt  Score    Error  Units
    test3_UsingForEachAndJava8         avgt  10   0.308 ±  0.021  µs/op
    test10_UsingEclipseMap             avgt  10   0.309 ±  0.009  µs/op
    test1_UsingWhileAndMapEntry        avgt  10   0.380 ±  0.014  µs/op
    test6_UsingForAndIterator          avgt  10   0.387 ±  0.016  µs/op
    test2_UsingForEachAndMapEntry      avgt  10   0.391 ±  0.023  µs/op
    test7_UsingJava8StreamApi          avgt  10   0.510 ±  0.014  µs/op
    test9_UsingApacheIterableMap       avgt  10   0.524 ±  0.008  µs/op
    test4_UsingKeySetAndForEach        avgt  10   0.816 ±  0.026  µs/op
    test5_UsingKeySetAndIterator       avgt  10   0.863 ±  0.025  µs/op
    test8_UsingJava8StreamApiParallel  avgt  10   5.552 ±  0.185  µs/op
    
  2. For map with 10000 elements, score 37.606 is the best

    对于包含10000个元素的地图,得分37.606是最好的

    Benchmark                           Mode   Cnt  Score      Error   Units
    test10_UsingEclipseMap              avgt   10    37.606 ±   0.790  µs/op
    test3_UsingForEachAndJava8          avgt   10    50.368 ±   0.887  µs/op
    test6_UsingForAndIterator           avgt   10    50.332 ±   0.507  µs/op
    test2_UsingForEachAndMapEntry       avgt   10    51.406 ±   1.032  µs/op
    test1_UsingWhileAndMapEntry         avgt   10    52.538 ±   2.431  µs/op
    test7_UsingJava8StreamApi           avgt   10    54.464 ±   0.712  µs/op
    test4_UsingKeySetAndForEach         avgt   10    79.016 ±  25.345  µs/op
    test5_UsingKeySetAndIterator        avgt   10    91.105 ±  10.220  µs/op
    test8_UsingJava8StreamApiParallel   avgt   10   112.511 ±   0.365  µs/op
    test9_UsingApacheIterableMap        avgt   10   125.714 ±   1.935  µs/op
    
  3. For map with 100000 elements, score 1184.767 is the best

    对于包含100000个元素的地图,得分1184.767是最好的

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

Graphs (perfomance tests depending on map size)

图(基于地图大小的性能测试)

如何有效地迭代“Map”中的每个条目?

Table (perfomance tests depending on map size)

表(基于地图大小的性能测试)

          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.190    4.470    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.910
test7     0.473    2.448    5.668    9.790   12.125
test9     0.565    2.830    5.952   13.220   16.965
test4     0.808    5.012    8.813   13.939   17.407
test5     0.810    5.104    8.533   14.064   17.422
test8     5.173   12.499   17.351   24.671   30.403

All tests are on GitHub.

所有的测试都在GitHub上。

#3


219  

In Java 8 you can do it clean and fast using the new lambdas features:

在Java 8中,您可以使用新的lambdas特性来快速地完成它:

 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));

The type of k and v will be inferred by the compiler and there is no need to use Map.Entry anymore.

编译器将推断k和v的类型,不需要使用Map。条目了。

Easy-peasy!

非常简单!

#4


192  

Yes, the order depends on the specific Map implementation.

是的,顺序取决于特定的映射实现。

@ScArcher2 has the more elegant Java 1.5 syntax. In 1.4, I would do something like this:

@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();
  // ...
}

#5


98  

Typical code for iterating over a map is:

在地图上迭代的典型代码是:

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

HashMap is the canonical map implementation and doesn't make guarantees (or though it should not change order if no mutating operation are performed on it). SortedMap will return entries based on the natural ordering of the keys, or a Comparator, if provided. LinkedHashMap will either return entries in insertion-order or access-order depending upon how it has been constructed. EnumMap returns entries in natural order of keys.

HashMap是规范的map实现,并没有做出保证(或者,如果在它上没有进行突变操作,它不应该改变顺序)。SortedMap将根据键的自然顺序返回条目,如果提供的话,还将返回一个比较器。LinkedHashMap要么以插入顺序返回条目,要么以访问顺序返回条目,这取决于它是如何构造的。EnumMap以自然顺序的键返回条目。

(Update: I think this is no longer true.) Note, IdentityHashMap entrySet iterator currently has a peculiar implementation which returns the same Map.Entry instance for every item in the entrySet! However, every time a new the iterator advances the Map.Entry is updated.

(更新:我认为这已经不是真的了。)注意,IdentityHashMap entrySet迭代器当前有一个特殊的实现,它返回相同的映射。每个条目的入口实例!但是,每当一个新的迭代器推进映射时。条目更新。

#6


87  

Example of using iterator and generics:

使用迭代器和泛型的示例:

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

#7


76  

This is a two part question:

这是一个由两部分组成的问题:

How to iterate over the entries of a Map - @ScArcher2 has answered that perfectly.

如何遍历Map - @ScArcher2的条目已经很好地回答了这个问题。

What is the order of iteration - if you are just using Map, then strictly speaking, there are no ordering guarantees. So you shouldn't really rely on the ordering given by any implementation. However, the SortedMap interface extends Map and provides exactly what you are looking for - implementations will aways give a consistent sort order.

迭代的顺序是什么?如果您只是使用Map,那么严格地说,没有排序保证。所以你不应该依赖于任何实现给出的顺序。然而,SortedMap接口扩展了Map并提供了您所需要的东西——实现总是给出一致的排序顺序。

NavigableMap is another useful extension - this is a SortedMap with additional methods for finding entries by their ordered position in the key set. So potentially this can remove the need for iterating in the first place - you might be able to find the specific entry you are after using the higherEntry, lowerEntry, ceilingEntry, or floorEntry methods. The descendingMap method even gives you an explicit method of reversing the traversal order.

NavigableMap是——这是另一个有用的扩展与额外的方法寻找SortedMap下令在关键位置设置条目。这可能可以删除需要迭代的——你可能会发现使用higherEntry后的具体条目,lowerEntry ceilingEntry或floorEntry方法。下行映射方法甚至为您提供了一个反转遍历顺序的显式方法。

#8


62  

There are several ways to iterate over map.

有几种方法可以迭代映射。

Here is comparison of their performances for a common data set stored in map by storing a million key value pairs in map and will iterate over map.

下面是它们对存储在map中的公共数据集的性能的比较,通过在map中存储一百万对键值对并在map上迭代。

1) Using entrySet() in for each loop

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

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

50 milliseconds

50毫秒

2) Using keySet() in for each loop

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

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

76 milliseconds

76毫秒

3) Using entrySet() and iterator

3)使用entrySet()和iterator

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

50 milliseconds

50毫秒

4) Using keySet() and iterator

4)使用keySet()和iterator

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

75 milliseconds

75毫秒

I have referred this link.

我已经提到了这个链接。

#9


41  

FYI, you can also use map.keySet() and map.values() if you're only interested in keys/values of the map and not the other.

顺便说一下,如果您只对map. keyset()和map.values()感兴趣,那么也可以使用map. keyset()和map.values()。

#10


40  

The correct way to do this is to use the accepted answer as it is the most efficient. I find the following code looks a bit cleaner.

正确的做法是使用公认的答案,因为它是最有效的。我发现下面的代码看起来更简洁一些。

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

#11


21  

With Eclipse Collections (formerly GS Collections), you would use the forEachKeyValue method on the MapIterable interface, which is inherited by the MutableMap and ImmutableMap interfaces and their implementations.

使用Eclipse集合(以前是GS集合),您将在MapIterable接口上使用forEachKeyValue方法,它由MutableMap和ImmutableMap接口及其实现继承。

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);

With Java 8 lambda syntax, you can write the code as follows:

使用Java 8 lambda语法,可以编写如下代码:

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);

Note: I am a committer for Eclipse Collections.

注意:我是Eclipse集合的提交者。

#12


19  

Try this with Java 1.4:

用Java 1.4试试这个:

for( Iterator entries = myMap.entrySet().iterator(); entries.hasNext();){

  Entry entry = (Entry) entries.next();

  System.out.println(entry.getKey() + "/" + entry.getValue());

  //...
}

#13


18  

Java 8:

Java 8:

You can use lambda expressions:

你可以使用lambda表达式:

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

For more information, follow this.

要了解更多信息,请遵循以下步骤。

#14


17  

In theory, the most efficient way will depend on which implementation of Map. The official way to do this is to call map.entrySet(), which returns a set of Map.Entry, each of which contains a key and a value (entry.getKey() and entry.getValue()).

理论上,最有效的方法将取决于映射的实现。正式的方法是调用Map. entryset(),它返回一组映射。条目,每个条目都包含一个键和一个值(entr. getkey()和entr. getvalue())。

In an idiosyncratic implementation, it might make some difference whether you use map.keySet(), map.entrySet() or something else. But I can't think of a reason why anyone would write it like that. Most likely it makes no difference to performance what you do.

在特殊的实现中,使用map.keySet()、map.entrySet()或其他东西可能会有所不同。但是我想不出为什么有人会这样写。很可能你所做的对表现没有影响。

And yes, the order will depend on the implementation - as well as (possibly) the order of insertion and other hard-to-control factors.

是的,顺序将取决于实现,以及(可能的)插入顺序和其他难以控制的因素。

[edit] I wrote valueSet() originally but of course entrySet() is actually the answer.

[编辑]我最初编写了valueSet(),但当然entrySet()实际上就是答案。

#15


15  

In Map one can Iteration over keys and/or values and/or both (e.g., entrySet) depends on one's interested in_ Like:

在Map中,一个人可以迭代键和/或值以及/或两者(例如,entrySet),这取决于他的兴趣所在:

1.) Iterate through the keys -> keySet() of the map:

1)。遍历map的key -> keySet():

Map<String, Object> map = ...;

for (String key : map.keySet()) {
    //your Business logic...
}

2.) Iterate through the values -> values() of the map:

2)。遍历映射的值->值():

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

3.) Iterate through the both -> entrySet() of the map:

3)。遍历map的-> entrySet():

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

Moreover, there are 3 difference ways to Iterate Through a HashMap. They are as below_

此外,有三种不同的方法可以遍历HashMap。他们是below_

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

#16


15  

Lambda Expression Java 8

Lambda表达式Java 8

In Java 1.8 (Java 8) this has become lot easier by using forEach method from Aggregate operations(Stream operations) that looks similar to iterators from Iterable Interface.

在Java 1.8 (Java 8)中,通过使用聚合操作(流操作)中的forEach方法,这变得容易得多,这种方法看起来类似于迭代接口中的迭代器。

Just copy paste below statement to your code and rename the HashMap variable from hm to your HashMap variable to print out key-value pair.

只需将下面的语句复制到代码中,并将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.

Below is the sample code that i tried using Lambda Expression. This stuff is so cool. Must try.

下面是我尝试使用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

Also one can use Spliterator for the same.

同样也可以使用Spliterator。

Spliterator sit = hm.entrySet().spliterator();

UPDATE

更新


Including documentation links to Oracle Docs. For more on Lambda go to this link and must read Aggregate Operations and for Spliterator go to this link.

包括文档链接到Oracle文档。有关Lambda的更多信息,请转到该链接,并必须读取聚合操作,Spliterator转到该链接。

#17


14  

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

OR

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();
        }
    }
}

#18


12  

If you have a generic untyped Map you can use:

如果你有一个通用的非类型化地图,你可以使用:

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

#19


8  

    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());    
    }

#20


7  

You can do it using generics:

你可以使用泛型:

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());
}

#21


6  

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

The best way is entrySet() though.

最好的方法是entrySet()。

#22


5  

           //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();

            }

#23


5  

Yes, as many people agreed this is the best way to iterate over a Map.

是的,很多人都认为这是迭代地图的最佳方式。

But there are chances to throw nullpointerexception if the map is null. Don't forget to put null .check in.

但是如果映射是空的,则有可能抛出nullpointerexception。不要忘记输入null。check in。

                                                 |
                                                 |
                                         - - - -
                                       |
                                       |
for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
}

#24


4  

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

#25


3  

If your reason for iterating trough the Map, is to do an operation on the value and write to a resulting Map. I recommend using the transform-methods in the Google Guava Maps class.

如果您迭代映射的原因是对值执行操作并写入结果映射。我建议在谷歌番石榴映射类中使用转换方法。

import com.google.common.collect.Maps;

After you have added the Maps to your imports, you can use Maps.transformValues and Maps.transformEntries on your maps, like this:

将映射添加到导入之后,就可以使用映射了。transformValues和地图。变换地图上的条目,比如:

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

#26


3  

In Java 8 we have got forEach method that accepts a lambda expression. We have also got stream APIs. Consider a map:

在Java 8中,我们有forEach方法,它接受lambda表达式。我们也有流api。考虑一个地图:

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

Iterate over keys:

遍历键:

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

Iterate over values:

遍历值:

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

Iterate over entries (Using forEach and Streams):

迭代条目(使用forEach和Streams):

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

The advantage with streams is they can be parallelized easily in case we want to. We simply need to use parallelStream() in place of stream() above.

流的优点是它们可以很容易地并行化,以备我们需要。我们只需要在上面的stream()中使用parallelStream()。

#27


3  

There are a lot of ways to do this. Below is a few simple steps:

有很多方法可以做到这一点。下面是一些简单的步骤:

Suppose you have one Map like:

假设你有一张这样的地图:

Map<String, Integer> m = new HashMap<String, Integer>();

Then you can do something like the below to iterate over map elements.

然后您可以执行如下操作来遍历映射元素。

// ********** Using an iterator ****************
Iterator<Entry<String, Integer>> me = m.entrySet().iterator();
while(me.hasNext()){
    Entry<String, Integer> pair = me.next();
    System.out.println(pair.getKey() + ":" + pair.getValue());
}

// *********** Using foreach ************************
for(Entry<String, Integer> me : m.entrySet()){
    System.out.println(me.getKey() + " : " + me.getValue());
}

// *********** Using keySet *****************************
for(String s : m.keySet()){
    System.out.println(s + " : " + m.get(s));
}

// *********** Using keySet and iterator *****************
Iterator<String> me = m.keySet().iterator();
while(me.hasNext()){
    String key = me.next();
    System.out.println(key + " : " + m.get(key));
}

#28


2  

It doesn't quite answer the OP's question, but might be useful to others who find this page:

它并没有很好地回答OP的问题,但是可能对发现这个页面的其他人有用:

If you only need the values and not the keys, you can do this:

如果你只需要值而不需要键,你可以这样做:

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

Ktype, Vtype are pseudocode.

Ktype,Vtype伪代码。

#29


2  

Here is a generic type-safe method which can be called to dump any given Map.

这里有一个通用的类型安全方法,可以调用它来转储任何给定的映射。

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

Example

Here is an example of its use. Notice that the type of the Map is inferred by the method.

这里有一个使用它的例子。注意,映射的类型是由方法推断的。

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();
        }
    }
}

Output

One = 0
Two = 1
Three = 3

Object = java.lang.Object@15db9742
Integer = 0
Double = 0.0

#30


2  

The ordering will always depend on the specific map implementation. Using Java 8 you can use either of these:

排序始终取决于特定的映射实现。使用Java 8,您可以使用以下任何一种:

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

Or:

或者:

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

The result will be the same (same order). The entrySet backed by the map so you are getting the same order. The second one is handy as it allows you to use lambdas, e.g. if you want only to print only Integer objects that are greater than 5:

结果是相同的(顺序相同)。由映射支持的入口集,因此您将得到相同的顺序。第二种方法很方便,因为它允许您使用lambdas,例如,如果您只想打印大于5的整数对象:

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

The code below shows iteration through LinkedHashMap and normal HashMap (example). You will see difference in the order:

下面的代码通过LinkedHashMap和normal HashMap(示例)显示了迭代。您将看到顺序上的差异:

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() + ", ");
        });
    }
}

LinkedHashMap (1):

LinkedHashMap(1):

10 (#=10):10, 9 (#=9):9, 8 (#=8):8, 7 (#=7):7, 6 (#=6):6, 5 (#=5):5, 4 (#=4):4, 3 (#=3):3, 2 (#=2):2, 1 (#=1):1, 0 (#=0):0,

10(# = 10):9(# = 9):9,8(# = 8):8、7(# = 7):7,6(# = 6):6,5(# = 5):5、4(# = 4):4 3(# = 3):3,2(# = 2):2、1(# = - 1):1,0(# = 0):0,

LinkedHashMap (2):

LinkedHashMap(2):

10 : 10, 9 : 9, 8 : 8, 7 : 7, 6 : 6, 5 : 5, 4 : 4, 3 : 3, 2 : 2, 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: 0,

HashMap (1):

HashMap(1):

0 (#:0):0, 1 (#:1):1, 2 (#:2):2, 3 (#:3):3, 4 (#:4):4, 5 (#:5):5, 6 (#:6):6, 7 (#:7):7, 8 (#:8):8, 9 (#:9):9, 10 (#:10):10,

0(#:0):0、1(#:1):1、2(#:2):2、3(#:3):3、4(#:4):4、5(#:5):5、6(#:6):6、7(#:7):7、8(#:8):8、9(#:9):9,10(#:10):10

HashMap (2):

HashMap(2):

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

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