优秀的编程知识分享平台

网站首页 > 技术文章 正文

Java中如何迭代Map中的每条数据? map的迭代器什么时候失效

nanyue 2024-12-18 16:01:29 技术文章 5 ℃

基于Map接口实现的对象,包含大量数据,希望对其中包含的对象进行迭代,可以使用那些方式呢?

Talk is cheap, Show me the code. -- by: Linus Torvalds

方式一、

使用 iterator ,代码如下:

// 创建Map对象
Map<String, String> map = new HashMap<>();
// 放入数据略
// ......

// 获取 iterator
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
// 判断是否有下一个元素
while (it.hasNext()) {
    // 获取下一个元素
    Map.Entry<String, String> next = it.next();
    // 输出 key, val
    System.out.println("key: " + next.getKey() + "  val: " + next.getValue());
}

方式二、

entrySet 配合增强for,代码如下:

// 创建Map对象
Map<String, String> map = new HashMap<>();
// 放入数据略
// ......

// 增加for遍历entrySet
for (Map.Entry<String, String> entry : map.entrySet()) {
    // 输出 key, val
    System.out.println("key: " + entry.getKey() + "  val: " + entry.getValue());
}

方式三、

keySet 配合增强for,代码如下:

// 创建Map对象
Map<String, String> map = new HashMap<>();
// 放入数据略
// ......

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

方式四、

使用 Java8新特性forEach ,代码如下:

// 创建Map对象
Map<String, String> map = new HashMap<>();
// 放入数据略
// ......

map.forEach((key, val) -> {
    // 输出 key, val
    System.out.println("key: " + key + "  val: " + val);
});

以上几种是常用的Map遍历(迭代)方式,选择自己喜欢的方式!

Tags:

最近发表
标签列表