如何在java中迭代Map?

时间:2017-03-25 10:10:36

标签: java loops hashmap iterator initialization

我需要遍历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;
}

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

3 个答案:

答案 0 :(得分: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());
    }
}

快速解释:

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

意味着:“对于地图键中的所有字符串,我们都会做一些事情,并且在每次迭代时我们都会调用键'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;
}

答案 1 :(得分:3)

看看这是否有帮助,

error_reporting(E_ALL)

答案 2 :(得分:0)

对于Java 8,我建议您使用Stream API。

它将允许您以更方便的方式遍历地图:

public void iterateUsingStreamAPI(Map<String, Integer> map) {
    map.entrySet().stream()
      // ...
      .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
}

查看有关iteration through maps in Java的更多示例。