java - 如何在 Java 中遍历 Map?

标签 java loops hashmap iterator initialization

我需要遍历 BucketMap 并获取所有 keys 但我如何获得类似 buckets[i].next.next.next 的内容。 key 例如我在此处尝试时无需手动执行:

public String[] getAllKeys() {
    //index of string array "allkeys"
    int j = 0;
    String allkeys[] = new String[8];
    //iterates through the bucketmap
    for (int i = 0; i < buckets.length; i++) {
        //checks wether bucket has a key and value
        if (buckets[i] != null) {
            //adds key to allkeys
            allkeys[j] = buckets[i].key;
            // counts up the allkeys index after adding key
            j++;
            //checks wether next has a key and value
            if (buckets[i].next != null) {
                //adds key to allkeys
                allkeys[j] = buckets[i].next.key;
                j++;
            }
        }
    }
    return allkeys;
}

另外,如何使用迭代完成后获得的 j 版本作为索引来初始化 String[] allkeys

最佳答案

对于基本使用,HashMap 是最好的,我已经介绍了如何迭代它,比使用迭代器更容易:

public static void main (String[] args) {
    //a map with key type : String, value type : String
    Map<String,String> mp = new HashMap<String,String>();
    mp.put("John","Math");    mp.put("Jack","Math");    map.put("Jeff","History");

    //3 differents ways to iterate over the map
    for (String key : mp.keySet()){
        //iterate over keys
        System.out.println(key+" "+mp.get(key));
    }

    for (String value : mp.values()){
        //iterate over values
        System.out.println(value);
    }

    for (Entry<String,String> pair : mp.entrySet()){
        //iterate over the pairs
        System.out.println(pair.getKey()+" "+pair.getValue());
    }
}

快速解释:

for (String name : mp.keySet()){
        //Do Something
}

意思是:“对于来自 map 键的所有字符串,我们将做一些事情,并且在每次迭代中我们将调用键'name'(它可以是你想要的任何东西,它是一个变量)


开始吧:

public String[] getAllKeys(){ 
    int i = 0;
    String allkeys[] = new String[buckets.length];
    KeyValue val = buckets[i];

    //Look at the first one          
    if(val != null) {             
        allkeys[i] = val.key; 
        i++;
    }

    //Iterate until there is no next
    while(val.next != null){
        allkeys[i] = val.next.key;
        val = val.next;
        i++;
    }

    return allkeys;
}

关于java - 如何在 Java 中遍历 Map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43015098/

相关文章:

java - Android - Java - 传输/接收十六进制值

java - 将 map 列表合并为单个 map

java - 灰熊队 Jersey : Getting MessageBodyWriter not found for media type=application/json

java - 在 Spring Hibernate 中操作 JSON 数组

java - 哈希表、ConcurrentHashMap 和数据可见性

java - 如何使用 Jackson 将 JSON 对象转换为 Java HashMap?

linux - 在引导过程后检查操作系统是否启动

python - 迭代时出现索引错误

javascript - 遍历对象数组?

java - HashSet 的 Hashing 是如何工作的?