如何在java中遍历Map? [英] How to iterate through a Map in java?

查看:17
本文介绍了如何在java中遍历Map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遍历 BucketMap 并获取所有 keys,但我如何获得类似 buckets[i].next.next.next 的内容.键 例如,无需像我在这里尝试的那样手动操作:

I need to iterate through a BucketMap and get all keys but how do I get to something like buckets[i].next.next.next.key for instance without doing it manually as I tried here:

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?

Also how can I initialize the String[] allkeys using the version of j we get after the iteration is done as the index?

推荐答案

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

For basic utilisation, the HashMap is the best, I've put how to iterate over it, easier than using an iterator :

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'(它可以是任何你想要的,它是一个变量)

means : "For all string from the keys of the map, we'll do something, and at each iteration we will call the key 'name' (it can be whatever you want, it's a variable)

我们开始吧:

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中遍历Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆