How to iterate through a Map in java?

前端 未结 3 426
囚心锁ツ
囚心锁ツ 2021-02-01 06:22

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 witho

3条回答
  •  一整个雨季
    2021-02-01 06:56

    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 mp = new HashMap();
        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 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)


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

提交回复
热议问题