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

发布于 2024-07-05 15:52:40 字数 97 浏览 9 评论 0 原文

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

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

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?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

宣告ˉ结束 2024-07-12 15:52:40

Java 8

我们有 forEach 方法,它接受 lambda 表达式。 我们还有 stream蜜蜂。 考虑一个映射:

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

迭代条目(使用 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);
        });

流的优点是它们可以如果我们愿意的话,可以很容易地并行化。 我们只需使用 parallelStream() 代替上面的 stream() 即可。

forEachOrdered 与带有流的 forEach
forEach 不遵循遇到顺序(如果已定义),并且本质上是不确定的,而 forEachOrdered 则不然。 所以 forEach 不保证顺序会被保留。 另请查看了解更多信息。

Java 8

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

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

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.

forEachOrdered vs forEach with streams ?
The forEach does not follow encounter order (if defined) and is inherently non-deterministic in nature where as the forEachOrdered does. So forEach does not guarantee that the order would be kept. Also check this for more.

茶花眉 2024-07-12 15:52:40

您可以使用泛型来做到这一点:

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

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());
}
猫九 2024-07-12 15:52:40

使用Java 8:

map.entrySet().forEach(entry -> System.out.println(entry.getValue()));

Use Java 8:

map.entrySet().forEach(entry -> System.out.println(entry.getValue()));
素罗衫 2024-07-12 15:52:40

对 Map 的有效迭代解决方案是从 Java 5 到 Java 7 的 for 循环。如下所示:

for (String key : phnMap.keySet()) {
    System.out.println("Key: " + key + " Value: " + phnMap.get(key));
}

从 Java 8 开始,您可以使用 lambda 表达式对 Map 进行迭代。 它是一个增强的 forEach

phnMap.forEach((k,v) -> System.out.println("Key: " + k + " Value: " + v));

如果你想为 lambda 编写一个条件,你可以这样写:

phnMap.forEach((k,v) -> {
    System.out.println("Key: " + k + " Value: " + v);
    if ("abc".equals(k)) {
        System.out.println("Hello abc");
    }
});

An effective iterative solution over a Map is a for loop from Java 5 through Java 7. Here it is:

for (String key : phnMap.keySet()) {
    System.out.println("Key: " + key + " Value: " + phnMap.get(key));
}

From Java 8, you can use a lambda expression to iterate over a Map. It is an enhanced forEach

phnMap.forEach((k,v) -> System.out.println("Key: " + k + " Value: " + v));

If you want to write a conditional for lambda you can write it like this:

phnMap.forEach((k,v) -> {
    System.out.println("Key: " + k + " Value: " + v);
    if ("abc".equals(k)) {
        System.out.println("Hello abc");
    }
});
终陌 2024-07-12 15:52:40

是的,顺序取决于具体的 Map 实现。

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

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:

Iterator entries = myMap.entrySet().iterator();
while (entries.hasNext()) {
  Entry thisEntry = (Entry) entries.next();
  Object key = thisEntry.getKey();
  Object value = thisEntry.getValue();
  // ...
}
旧人 2024-07-12 15:52:40
Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}

在 Java 10+ 上:

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

On Java 10+:

for (var entry : map.entrySet()) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}
哽咽笑 2024-07-12 15:52:40

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

  1. 使用迭代器Map.Entry

    长 i = 0; 
      迭代器>   it = map.entrySet().iterator(); 
      while (it.hasNext()) { 
          Map.Entry<整数, 整数>   对 = it.next(); 
          i +=pair.getKey() +pair.getValue(); 
      } 
      
  2. 使用foreachMap.Entry >

    长 i = 0; 
      for (Map.Entry 对: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

    长 i = 0; 
      for (整数键:map.keySet()) { 
          i += key + map.get(key); 
      } 
      
  5. 使用keySet迭代器

    长 i = 0; 
      迭代器<整数>   itr2 = map.keySet().iterator(); 
      while (itr2.hasNext()) { 
          整数键 = itr2.next(); 
          i += key + map.get(key); 
      } 
      
  6. 使用forMap.Entry< /p>

    长i = 0; 
      for (Iterator>entrys = map.entrySet().iterator();entrys.hasNext();) { 
          Map.Entry<整数, 整数>   条目=条目.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 CollectionsIterableMap

    长i = 0; 
      MapIterator<整数, 整数>   it = iterableMap.mapIterator(); 
      while (it.hasNext()) { 
          i += it.next() + it.getValue(); 
      } 
      
  10. 使用 Eclipse (CS) 集合的 MutableMap

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

性能测试(模式 = AverageTime,系统 = Windows 8.1 64 位、Intel i7-4790 3.60 GHz,16 GB)

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

    基准模式 Cnt 分数错误单位 
      test3_UsingForEachAndJava8 avgt 10 0.308 ± 0.021 µs/操作 
      test10_UsingEclipseMap avgt 10 0.309 ± 0.009 µs/操作 
      test1_UsingWhileAndMapEntry avgt 10 0.380 ± 0.014 µs/操作 
      test6_UsingForAndIterator avgt 10 0.387 ± 0.016 µs/操作 
      test2_UsingForEachAndMapEntry avgt 10 0.391 ± 0.023 µs/操作 
      test7_UsingJava8StreamApi avgt 10 0.510 ± 0.014 µs/操作 
      test9_UsingApacheIterableMap avgt 10 0.524 ± 0.008 µs/操作 
      test4_UsingKeySetAndForEach avgt 10 0.816 ± 0.026 µs/操作 
      test5_UsingKeySetAndIterator avgt 10 0.863 ± 0.025 µs/操作 
      test8_UsingJava8StreamApiParallel avgt 10 5.552 ± 0.185 µs/op 
      
  2. 对于 10000 个元素的地图,分数 37.606 是最佳

    基准模式 Cnt 分数错误单位 
      test10_UsingEclipseMap avgt 10 37.606 ± 0.790 µs/操作 
      test3_UsingForEachAndJava8 avgt 10 50.368 ± 0.887 µs/操作 
      test6_UsingForAndIterator avgt 10 50.332 ± 0.507 µs/操作 
      test2_UsingForEachAndMapEntry avgt 10 51.406 ± 1.032 µs/操作 
      test1_UsingWhileAndMapEntry avgt 10 52.538 ± 2.431 µs/操作 
      test7_UsingJava8StreamApi avgt 10 54.464 ± 0.712 µs/操作 
      test4_UsingKeySetAndForEach avgt 10 79.016 ± 25.345 µs/操作 
      test5_UsingKeySetAndIterator avgt 10 91.105 ± 10.220 µs/操作 
      test8_UsingJava8StreamApiParallel avgt 10 112.511 ± 0.365 µs/op 
      test9_UsingApacheIterableMap avgt 10 125.714 ± 1.935 µs/操作 
      
  3. 对于具有 100000 个元素的地图,分数 1184.767 是最佳

    基准模式 Cnt 分数错误单位 
      test1_UsingWhileAndMapEntry avgt 10 1184.767 ± 332.968 µs/op 
      test10_UsingEclipseMap avgt 10 1191.735 ± 304.273 µs/操作 
      test2_UsingForEachAndMapEntry avgt 10 1205.815 ± 366.043 µs/op 
      test6_UsingForAndIterator avgt 10 1206.873 ± 367.272 µs/操作 
      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/操作 
      test3_UsingForEachAndJava8 avgt 10 1666.296 ± 126.443 µs/操作 
      test7_UsingJava8StreamApi avgt 10 1706.676 ± 436.867 µs/操作 
      test9_UsingApacheIterableMap avgt 10 3289.866 ± 1445.564 µs/操作 
      

图(性能测试取决于地图大小)

在此处输入图像描述

表(性能测试取决于地图大小)

          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

所有测试均在 < a href="https://github.com/Vedenin/useful-java-links/blob/master/helloworlds/5.0-other-examples/src/main/java/other_examples/IterateThroughHashMapTest.java" rel="noreferrer"> GitHub。

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:

  1. Using iterator and 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

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

    final long[] i = {0};
    map.forEach((k, v) -> i[0] += k + v);
    
  4. Using keySet and 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

    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

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

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

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

    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)

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

    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 a map with 10000 elements, score 37.606 is the best

    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 a map with 100000 elements, score 1184.767 is the best

    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 (performance tests depending on map size)

Enter image description here

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.

简单气质女生网名 2024-07-12 15:52:40

在 Java 8 中,您可以使用新的 lambda 功能干净、快速地完成此操作:

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

kv 的类型将由编译器推断,无需使用 <不再是代码>Map.Entry了。

十分简单!

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

 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.

Easy-peasy!

江湖正好 2024-07-12 15:52:40

使用Java 8,您可以使用 forEach 和 lambda 表达式迭代 Map,

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

With Java 8, you can iterate Map using forEach and lambda expression,

map.forEach((k, v) -> System.out.println((k + ":" + v)));
绮筵 2024-07-12 15:52:40

对于 Eclipse Collections,您可以在 forEachKeyValue 方法中使用 < a href="https://github.com/eclipse/eclipse-collections/blob/master/eclipse-collections-api/src/main/java/org/eclipse/collections/api/map/MapIterable.java" rel= "nofollow noreferrer">MapIterable 接口,由 MutableMapImmutableMap 接口及其实现继承。

MutableMap<Integer, String> map = 
    Maps.mutable.of(1, "One", 2, "Two", 3, "Three");

MutableBag<String> result = Bags.mutable.empty();
map.forEachKeyValue((key, value) -> result.add(key + value));

MutableBag<String> expected = Bags.mutable.of("1One", "2Two", "3Three");
Assertions.assertEquals(expected, result);

forEachKeyValue 与 Eclipse Collections (EC) Map 实现结合使用比使用 entrySet 更高效的原因是 EC Map > 实现不存储 Map.Entry 对象。 将 entrySet 与 EC Map 实现结合使用会导致动态生成 Map.Entry 对象。 forEachKeyValue 方法能够避免创建 Map.Entry 对象,因为它可以直接导航 Map 实现的内部结构。 在这种情况下,使用内部迭代器比使用外部迭代器更有好处。

注意:我是 Eclipse Collections 的提交者。

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

MutableMap<Integer, String> map = 
    Maps.mutable.of(1, "One", 2, "Two", 3, "Three");

MutableBag<String> result = Bags.mutable.empty();
map.forEachKeyValue((key, value) -> result.add(key + value));

MutableBag<String> expected = Bags.mutable.of("1One", "2Two", "3Three");
Assertions.assertEquals(expected, result);

The reason using forEachKeyValue with Eclipse Collections (EC) Map implementations will be more efficient than using entrySet is because EC Map implementations do not store Map.Entry objects. Using entrySet with EC Map implementations results in Map.Entry objects being generated dynamically. The forEachKeyValue method is able to avoid creating the Map.Entry objects because it can navigate the internal structure of the Map implementations directly. This is a case where there is a benefit of using an internal iterator over an external iterator.

Note: I am a committer for Eclipse Collections.

枕花眠 2024-07-12 15:52:40

正确的方法是使用已接受的答案,因为它是最有效的。 我发现下面的代码看起来更干净一些。

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

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));
}
好久不见√ 2024-07-12 15:52:40

仅供参考,如果您只对地图的键/值而不是其他感兴趣,您也可以使用 map.keySet()map.values()

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.

五里雾 2024-07-12 15:52:40

This is a two part question:

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

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.

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.

风启觞 2024-07-12 15:52:40

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

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

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();
  // ...
}
别忘他 2024-07-12 15:52:40

迭代映射的典型代码是:

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

HashMap 是规范的映射实现,并且不做出保证(或者如果没有对其执行变异操作,则它不应该更改顺序)。 SortedMap 将根据键的自然顺序返回条目,或者返回一个 Comparator(如果提供)。 LinkedHashMap 将按照插入顺序或访问顺序返回条目,具体取决于它的构造方式。 EnumMap 按键的自然顺序返回条目。

(更新:我认为这不再是正确的。)注意,IdentityHashMap entrySet 迭代器当前有一个特殊的实现,它返回相同的 entrySet 中每个项目的 Map.Entry 实例! 然而,每次新的迭代器前进时,Map.Entry都会更新。

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 the order if no mutating operations 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 the natural order of keys.

(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 iterator advances the Map.Entry is updated.

歌入人心 2024-07-12 15:52:40

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

如果循环键的效率是您的应用的首要任务,那么请选择一个 Map 实现来按您所需的顺序维护键。

元素的顺序是否取决于接口的特定地图实现?

是的,一点没错。

  • 一些 Map 实现承诺一定的迭代顺序,而其他实现则不承诺。
  • Map 的不同实现维护键值对的不同顺序。

请参阅我创建的表格,该表总结了与 Java 11 捆绑的各种 Map 实现。具体来说,请注意迭代顺序列。 单击/点击进行缩放。

地图表Java 11 中的实现,比较它们的功能

您可以看到有四个 Map 实现维持顺序

  • TreeMap
  • ConcurrentSkipListMap
  • LinkedHashMap
  • EnumMap

NavigableMap 接口

其中两个实现了 NavigableMap 接口:TreeMap< /代码> & ConcurrentSkipListMap

旧的 SortedMap 接口已被较新的 NavigableMap 接口。 但您可能会发现第三方实现仅实现旧接口。

自然顺序

如果您想要 Map 保持其对按键的“自然顺序”排列,请使用 TreeMapConcurrentSkipListMap。 术语“自然顺序”意味着键实现的类可比较compareTo方法用于排序时进行比较。

自定义顺序

如果要为键指定自定义排序例程以用于维护排序顺序,请传递 Comparator 实现适合您的键的类。 使用 TreeMapConcurrentSkipListMap,传递您的Comparator

原始插入顺序

如果您希望映射对保持插入映射时的原始顺序,请使用 LinkedHashMap

枚举定义顺序

如果您使用的是枚举,例如 DayOfWeekMonth 作为您的键,使用 EnumMap 类。 这个类不仅经过高度优化以使用很少的内存并且运行速度非常快,而且它按照枚举定义的顺序维护您的对。 以DayOfWeek为例,迭代时会先找到DayOfWeek.MONDAY的key,最后找到DayOfWeek.SUNDAY的key 。

其他注意事项

在选择 Map 实现时,还要考虑:

  • NULL。 某些实现禁止/接受 NULL 作为键和/或值。
  • 并发性。 如果要跨线程操作映射,则必须使用支持并发的实现。 或者用 Collections::synchronizedMap (不太可取)。

上面的图表涵盖了这两个注意事项。

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?

If efficiency of looping the keys is a priority for your app, then choose a Map implementation that maintains the keys in your desired order.

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

Yes, absolutely.

  • Some Map implementations promise a certain iteration order, others do not.
  • Different implementations of Map maintain different ordering of the key-value pairs.

See this table I created summarizing the various Map implementations bundled with Java 11. Specifically, notice the iteration order column. Click/tap to zoom.

Table of map implementations in Java 11, comparing their features

You can see there are four Map implementations maintaining an order:

  • TreeMap
  • ConcurrentSkipListMap
  • LinkedHashMap
  • EnumMap

NavigableMap interface

Two of those implement the NavigableMap interface: TreeMap & ConcurrentSkipListMap.

The older SortedMap interface is effectively supplanted by the newer NavigableMap interface. But you may find 3rd-party implementations implementing the older interface only.

Natural order

If you want a Map that keeps its pairs arranged by the “natural order” of the key, use TreeMap or ConcurrentSkipListMap. The term “natural order” means the class of the keys implements Comparable. The value returned by the compareTo method is used for comparison in sorting.

Custom order

If you want to specify a custom sorting routine for your keys to be used in maintaining a sorted order, pass a Comparator implementation appropriate to the class of your keys. Use either TreeMap or ConcurrentSkipListMap, passing your Comparator.

Original insertion order

If you want the pairs of your map to be kept in their original order in which you inserted them into the map, use LinkedHashMap.

Enum-definition order

If you are using an enum such as DayOfWeek or Month as your keys, use the EnumMap class. Not only is this class highly optimized to use very little memory and run very fast, it maintains your pairs in the order defined by the enum. For DayOfWeek, for example, the key of DayOfWeek.MONDAY will be first found when iterated, and the key of DayOfWeek.SUNDAY will be last.

Other considerations

In choosing a Map implementation, also consider:

  • NULLs. Some implementations forbid/accept a NULL as key and/or value.
  • Concurrency. If you are manipulating the map across threads, you must use an implementation that supports concurrency. Or wrap the map with Collections::synchronizedMap (less preferable).

Both of these considerations are covered in the graphic table above.

输什么也不输骨气 2024-07-12 15:52:40

这些都是迭代HashMap的可能方式。

HashMap<Integer,String> map = new HashMap<Integer,String>();
    map.put(1, "David"); // Adding elements to 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 (java 6 Method)
    for (Integer key : map.keySet()) {
        System.out.println(map.get(key));
    }

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

These are all the possible ways of iterating HashMap.

HashMap<Integer,String> map = new HashMap<Integer,String>();
    map.put(1, "David"); // Adding elements to 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 (java 6 Method)
    for (Integer key : map.keySet()) {
        System.out.println(map.get(key));
    }

    // way 4 (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());
    }   
}
被你宠の有点坏 2024-07-12 15:52:40

Java 8 最紧凑:

map.entrySet().forEach(System.out::println);

Most compact with Java 8:

map.entrySet().forEach(System.out::println);
请帮我爱他 2024-07-12 15:52:40

理论上,最有效的方法将取决于 Map 的实现。 官方的方法是调用map.entrySet(),它返回一组Map.Entry,其中每个包含一个键和一个值( >entry.getKey()entry.getValue())。

在特殊的实现中,无论您使用 map.keySet()map.entrySet() 还是其他东西,可能会有所不同。 但我想不出为什么有人会这样写。 最有可能的是,你所做的事情对性能没有影响。

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

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

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()).

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.

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.

各自安好 2024-07-12 15:52:40

排序始终取决于具体的地图实现。
使用 Java 8,您可以使用以下任一方法:

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

或者:

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

结果将是相同的(相同的顺序)。 EntrySet 由地图支持,因此您将获得相同的顺序。 第二个很方便,因为它允许您使用 lambda,例如,如果您只想打印大于 5 的 Integer 对象:

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

下面的代码显示了通过 LinkedHashMap 和普通 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):
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,
LinkedHashMap (2):
10 : 10, 9 : 9, 8 : 8, 7 : 7, 6 : 6, 5 : 5, 4 : 4, 3 : 3, 2 : 2, 1 : 1, 0 : 0,
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,
HashMap (2):
0 : 0, 1 : 1, 2 : 2, 3 : 3, 4 : 4, 5 : 5, 6 : 6, 7 : 7, 8 : 8, 9 : 9, 10 : 10,

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

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:

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:

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

Output:

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,
LinkedHashMap (2):
10 : 10, 9 : 9, 8 : 8, 7 : 7, 6 : 6, 5 : 5, 4 : 4, 3 : 3, 2 : 2, 1 : 1, 0 : 0,
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,
HashMap (2):
0 : 0, 1 : 1, 2 : 2, 3 : 3, 4 : 4, 5 : 5, 6 : 6, 7 : 7, 8 : 8, 9 : 9, 10 : 10,
酸甜透明夹心 2024-07-12 15:52:40

用 Java 1.4 试试这个:

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

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

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

  //...
}

Try this with Java 1.4:

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

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

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

  //...
}
山川志 2024-07-12 15:52:40

Java 8:

您可以使用 lambda 表达式:

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

有关详细信息,请遵循 这个

Java 8:

You can use lambda expressions:

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

For more information, follow this.

夏雨凉 2024-07-12 15:52:40

在 Map 中,人们可以对和/或和/或两者(例如,entrySet)进行迭代,具体取决于某人的兴趣_例如:

  1. 迭代 按键 -> 地图的 keySet()

    Map<字符串,对象>   地图=...; 
    
      for (字符串键:map.keySet()) { 
          //你的业务逻辑... 
      } 
      
  2. 迭代 值 -> 地图的values()

    for (对象值:map.values()) { 
          //你的业务逻辑... 
      } 
      
  3. 迭代两者 -> 地图的entrySet()

    for (Map.Entryentry : 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);
}

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

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

    Map<String, Object> map = ...;
    
    for (String key : map.keySet()) {
        //your Business logic...
    }
    
  2. Iterate through the values -> values() of the map:

    for (Object value : map.values()) {
        //your Business logic...
    }
    
  3. Iterate through the both -> entrySet() of the map:

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

Moreover, there are 3 different ways to iterate through a HashMap. They are as 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);
}
情定在深秋 2024-07-12 15:52:40

Lambda 表达式 Java 8

在 Java 1.8 (Java 8) 中,通过使用聚合操作(流操作)中的 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 的更多信息,请访问此链接< /a> 且必须阅读 聚合操作,对于 Spliterator,请转到此 < a href="https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html" rel="nofollow noreferrer">链接。

Lambda Expression 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.

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

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

放赐 2024-07-12 15:52:40
//Functional Operations
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();

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

}
千柳 2024-07-12 15:52:40

是的,正如许多人同意的那样,这是迭代 Map 的最佳方式。

但如果地图为 null,则有可能抛出 NullPointerException。 不要忘记输入 null .check in。

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

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.

                                                 |
                                                 |
                                         - - - -
                                       |
                                       |
for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
}
沉默的熊 2024-07-12 15:52:40

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

假设您有一个像这样的 Map:

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

然后您可以执行如下操作来迭代地图元素。

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

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));
}
逆光飞翔i 2024-07-12 15:52:40
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());    
}
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());    
}
别把无礼当个性 2024-07-12 15:52:40
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();
        }
    }
}
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();
        }
    }
}
雨落□心尘 2024-07-12 15:52:40

如果您有一个通用的无类型映射,您可以使用:

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

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());
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文