如何遍历java中的Map?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43015098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:36:16  来源:igfitidea点击:

How to iterate through a Map in java?

javaloopshashmapiteratorinitialization

提问by NoIdea

I need to iterate through a BucketMapand get all keysbut how do I get to something like buckets[i].next.next.next.keyfor instance without doing it manually as I tried here:

我需要遍历 aBucketMap并获取所有内容,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;
}

Also how can I initialize the String[] allkeysusing the version of jwe get after the iteration is done as the index?

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

采纳答案by azro

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

对于基本使用,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("Hyman","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());
    }
}

A quick explanation :

快速解释:

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

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)

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



Here we go :

开始了 :

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;
}

回答by DNAj

See if this helps,

看看这是否有帮助,

  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();
}

回答by Johnny

With Java 8, I would suggest you to use Stream API.

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

It will allow you to iterate through the Map in a much more convenient approach:

它将允许您以更方便的方法遍历 Map:

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

Check out for more examples about iteration through maps in Java.

查看有关Java 中映射迭代的更多示例。