新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

怎么遍历Java中的HashMap ,java遍历enumeration

发布时间:2024-07-30 10:03:09

怎样遍历Java中的HashMap

在Java中,可使用迭代器还是forEach循环来遍历HashMap。以下是两种经常使用的遍历HashMap的方法:

  1. 使用迭代器遍历HashMap:
HashMap<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");

Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, String> entry = iterator.next();
    System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
  1. 使用forEach循环遍历HashMap:
HashMap<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");

map.forEach((key, value) -> {
    System.out.println("Key: " + key + ", Value: " + value);
});

不管使用哪一种方法,都可以遍历HashMap并输出其中的键值对。请根据具体的需求选择合适的遍历方法。

tiktok粉丝购买:https://www.smmfensi.com/