Java 中HashMap的基本操作增删遍历

import java.util.*;

public class ArrayListRemove {

    //字符字符
    public static void HashMapDemo1(){
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("a", "AA");
        hashMap.put("b", "BB");
        hashMap.put("c", "CC");

        System.out.println(hashMap);//{a=AA, b=BB, c=CC}
        System.out.println("a:" + hashMap.get("a"));//a:AA
        System.out.println(hashMap.containsKey("a"));//true
        System.out.println(hashMap.keySet());//[a, b, c]
        System.out.println(hashMap.isEmpty());//false

        hashMap.remove("a");
        System.out.println(hashMap.containsKey("a"));//false

        //采用Iterator遍历HashMap
        Iterator it = hashMap.keySet().iterator();
        while(it.hasNext()) {
            String key = (String)it.next();
            System.out.println("key:" + key);
            System.out.println("value:" + hashMap.get(key));
//            key:b
//            value:BB
//            key:c
//            value:CC
        }
    }
    
    //字符列表
    public static void HashMapDemo2(){
        HashMap<String, List<String>> map = new HashMap<String, List<String>>();
        ArrayList<String> list1=new ArrayList<String>();
        list1.add("a");
        list1.add("aa");
        map.put("list1",list1);

        ArrayList<String> list2=new ArrayList<String>();
        list2.add("b");
        list2.add("bb");
        map.put("list2",list2);

        System.out.println(map);//{list1=[a, aa], list2=[b, bb]}
        System.out.println("list1:" + map.get("list1"));//list1:[a, aa]
        System.out.println(map.containsKey("list1"));//true
        System.out.println(map.keySet());//[list1, list2]
        System.out.println(map.isEmpty());//false

        map.remove("a");
        System.out.println(map.containsKey("a"));//false

        //采用Iterator遍历HashMap
        Iterator it = map.keySet().iterator();
        while(it.hasNext()) {
            String key = (String) it.next();
            System.out.println("key:" + key);
            System.out.println("value:" + map.get(key));
//            key:list1
//            value:[a, aa]
//            key:list2
//            value:[b, bb]
        }
    }

    public static void main(String[] args) {
        HashMapDemo1();
        HashMapDemo2();

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值