1

如何遍历HashMap集合? - news_one

 1 year ago
source link: https://www.cnblogs.com/new-one/p/17347653.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在Java中,HashMap是一种常用的数据结构,它提供了快速的查找、插入和删除操作。当我们需要遍历HashMap中的所有元素时,可以利用三种不同的方法实现。

方法一:使用键值对遍历

HashMap中存储的是键值对的形式,因此最简单的方法就是直接遍历键值对。我们可以通过以下代码实现:

// 创建一个HashMap对象
Map<Integer, String> hashMap = new HashMap<Integer, String>();
// 将元素添加到HashMap中
hashMap.put(1, "One");
hashMap.put(2, "Two");
hashMap.put(3, "Three");

// 遍历HashMap中的键值对
for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
    Integer key = entry.getKey();
    String value = entry.getValue();
    System.out.println(key + ": " + value);
}

上述代码中,我们首先创建了一个HashMap对象,并将三个元素添加到其中。然后我们使用entrySet()方法获取键值对的集合,使用for循环遍历该集合,并通过getKey()和getValue()方法分别获取键和值。

方法二:使用键集合遍历

除了遍历键值对外,还可以直接遍历键的集合,通过键获取值即可。我们可以通过以下代码实现:

// 创建一个HashMap对象
Map<Integer, String> hashMap = new HashMap<Integer, String>();
// 将元素添加到HashMap中
hashMap.put(1, "One");
hashMap.put(2, "Two");
hashMap.put(3, "Three");

// 遍历HashMap中的键
for (Integer key : hashMap.keySet()) {
    String value = hashMap.get(key);
    System.out.println(key + ": " + value);
}

在上述代码中,我们首先创建了一个HashMap对象,并将三个元素添加到其中。然后我们使用keySet()方法获取键的集合,使用for循环遍历该集合,并通过get()方法获取对应的值。

方法三:使用值集合遍历

除了遍历键和键值对外,还可以直接遍历值的集合。我们可以通过以下代码实现:

// 创建一个HashMap对象
Map<Integer, String> hashMap = new HashMap<Integer, String>();
// 将元素添加到HashMap中
hashMap.put(1, "One");
hashMap.put(2, "Two");
hashMap.put(3, "Three");

// 遍历HashMap中的值
for (String value : hashMap.values()) {
    System.out.println(value);
}

在上述代码中,我们首先创建了一个HashMap对象,并将三个元素添加到其中。然后我们使用values()方法获取值的集合,使用for循环遍历该集合即可。

以下是完整的源码:

import java.util.HashMap;
import java.util.Map;

public class HashMapTraversal {
    public static void main(String[] args) {
        // 创建一个HashMap对象
        Map<Integer, String> hashMap = new HashMap<Integer, String>();
        // 将元素添加到HashMap中
        hashMap.put(1, "One");
        hashMap.put(2, "Two");
        hashMap.put(3, "Three");

        // 遍历HashMap中的键值对
        for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
            Integer key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + ": " + value);
        }

        // 遍历HashMap中的键
        for (Integer key : hashMap.keySet()) {
            String value = hashMap.get(key);
            System.out.println(key + ": " + value);
        }

        // 遍历HashMap中的值
        for (String value : hashMap.values()) {
            System.out.println(value);
        }
    }
}

可以根据上述三种遍历方法的需求,选择相应的方式进行遍历。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK