专业的JAVA编程教程与资源

网站首页 > java教程 正文

Java中如何迭代Map中的每条数据?(java中map的遍历方法)

temp10 2024-10-26 15:24:51 java教程 23 ℃ 0 评论

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

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

Java中如何迭代Map中的每条数据?(java中map的遍历方法)

方式一、

使用 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:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表