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, "zero.dengc@outlook.com");
        // 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, "zero.dengC@outlook.com");

        // 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());
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值