如何在java中迭代Map?

NoI*_*dea 19 java iterator loops initialization hashmap

我需要遍历a BucketMap并获取所有内容,keys但是如何在不buckets[i].next.next.next.key尝试手动操作的情况下进行操作,如我在此处尝试的那样:

public String[] getAllKeys() {

    int j = 0;      //index of string array "allkeys"

    String allkeys[] = new String[8];

    for(int i = 0; i < buckets.length; i++) { //iterates through the bucketmap

        if(buckets[i] != null) {             //checks wether bucket has a key and value
            allkeys[j] = buckets[i].key;     //adds key to allkeys
            j++;                             // counts up the allkeys index after adding key

            if(buckets[i].next != null) {         //checks wether next has a key and value
                allkeys[j] = buckets[i].next.key; //adds key to allkeys
                j++;
            }
        }
    }

    return allkeys;
}
Run Code Online (Sandbox Code Playgroud)

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

azr*_*zro 44

对于基本的利用,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());
    }
}
Run Code Online (Sandbox Code Playgroud)

快速解释:

for (String name : mp.keySet()){
        //Do Something
}
Run Code Online (Sandbox Code Playgroud)

意思是:"对于地图键中的所有字符串,我们会做一些事情,并且在每次迭代时我们都会调用键'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;
}
Run Code Online (Sandbox Code Playgroud)