Simple Operation of HashMap and HashTable

HashMap Iterator and ForEach

package com.jet;

import java.util.*;

public class AbstractFactory {
    
    
    public static void main(String[] args){
    
    
        // Creating a HashMap of int keys and String values
        Map<Integer, String> map = new HashMap<>();
        // Adding key and value pairs to map
        map.put(1, "Deng");
        map.put(2, "jet5devil");
        map.put(4, "[email protected]");
        // Getting a set of key-value pairs
        Set entrySet = map.entrySet();
        // Obtaining an iterator for the entry set
        Iterator in = entrySet.iterator();
        // First method: Iterator though map entries(key-value pairs)
        while(in.hasNext()){
    
    
            Map.Entry entry = (Map.Entry) in.next();
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }
        // Second method: foreach out result use map's entrySet()
        for(Map.Entry<Integer, String> entry : map.entrySet()){
    
    
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }
    }
}

HashTable

package com.jet;

import java.util.*;

public class AbstractFactory {
    
    
    public static void main(String[] args){
    
    
        Hashtable<Integer, String> hashtable = new Hashtable<>();
        hashtable.put(0, "Deng");
        hashtable.put(1, "jet5devil");
        hashtable.put(2, "[email protected]");

        // elements()
        Set entrySet = hashtable.entrySet();
        Iterator iterator = entrySet.iterator();
        while (iterator.hasNext()){
    
    
            Map.Entry<Integer, String> in = (Map.Entry) iterator.next();
            System.out.println("key is:"+in.getKey()+":value is:"+in.getValue());
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41288824/article/details/108786111