如何在Java中遍历Map?

20
我需要遍历一个BucketMap并获取所有的键,但如果我想获取类似于bucktes[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;
}

还有,我该如何使用迭代结束后得到的版本 j 作为索引来初始化 String[] allkeys


1
你也可以阅读Map的JavaDoc,找到一个更简单的方法来获取所有键... - Tom
好的,这是一个映射。它有一个键、一个值和下一个。 - NoIdea
你能不能提供创建'bucket'的那一行代码呢?你是想要帮助还是不想要?^^ - azro
1
那么你创建了一种 LinkedMap?为什么不使用已有的实现? - azro
1
如果它是一个 Map,只需获取 keySet() 并通过 for(String key : bucketMap.keySet()) 进行迭代。在这里,entry 的类型是 Map 的值,例如 List、Map、Class 等。也就是说,如果 Map<key, List<Value>>,那么 List<value> = buckeyMap.get(key)。 - Mikenno
显示剩余5条评论
3个回答

52

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

3
看看这是否有帮助,
  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();
}

2

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

它将允许您以更方便的方式迭代Map:

最初的回答:

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

请查看更多关于在Java中遍历映射的示例:最初的回答

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接