如何在java中迭代Map?

2022-09-02 05:22:41

我需要迭代一个并获取所有内容,但是我如何获得类似的东西,例如,当我在这里尝试时,无需手动执行此操作:BucketMapkeysbuckets[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;
}

另外,我如何初始化使用迭代完成后我们得到的版本作为索引?String[] allkeysj


答案 1

对于基本的利用,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
}

means :“对于映射键中的所有字符串,我们将执行一些操作,并且在每次迭代时,我们将调用键'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;
}

答案 2

看看这是否有帮助,

  HashMap< String, String> map = new HashMap<>();
  Set<String> keySet = map.keySet();
  Iterator<String> iterator = keySet.iterator();
  while(iterator.hasNext())
  {
    //iterate over keys
  }

//or iterate over entryset 
Iterator<Entry<String, String>> iterator2 = map.entrySet().iterator();

while(iterator2.hasNext())
{
    Entry<String, String> next = iterator2.next();
    //get key
    next.getKey();
    //get value
    next.getValue();
}

推荐