Java大数据之路--映射(Map)

  • 映射(Map<K,V>)


K---键,V---值   由键得到值(唯一),键不能重复,把这一对数据(键和值)统称为键值对,一个映射是由多个键值对组成的。

为了方便操作键和值,就把键值对抽取成一个类------Map.Entry,Entry对象都是具体的键值对,一个映射可以由多个Entry兑现组成的。

遍历映射:

1、根据键来遍历

public class MapDemo1 {
    public static void main(String[] args) {
        //创建映射对象
        Map<String,Integer> map = new HashMap<>();
        //添加元素
        map.put("a",1);
        map.put("b",2);
        map.put("c",3);
        map.put("d",1);
        //1、获取映射中所有的键
        Set<String> set = map.keySet();
        //遍历键
        for (String string:set) {
            //由键获取值
            System.out.println(string+"="+map.get(string));
        }
    }

}

2、根据键值对来进行遍历

public class MapDemo2 {
    public static void main(String[] args) {
        //创建映射对象
        Map<String,Integer> map = new HashMap<>();
        //添加元素
        map.put("a",1);
        map.put("b",2);
        map.put("c",3);
        map.put("d",1);
        //2、根据键值对获取对应的键值遍历
//        Set<Map.Entry<String,Integer>> set = map.entrySet();
//        //遍历所有键值对---遍历set集合
//        for (Map.Entry<String, Integer> entry:set) {
//            //每个entry就是具体的entry对象就是键值对
//            System.out.println(entry.getKey()+"="+entry.getValue());
//        }
        for(Map.Entry<String,Integer> entry:map.entrySet()){
            System.out.println(entry.getKey()+"="+entry.getValue());
        }
    }
}

练习:通过映射来统计一个字符串中所有字符出现的次数

public class MapDemo3 {
    public static void main(String[] args) {
        //通过映射来统计一个字符串中所有字符出现的次数
        //键代表字符,值代表字符出现次数
        Map<String,Integer> map= new HashMap<>();
        String s = "dsfjaklfjkfklfdfjkweqruqcnmzc";
        //遍历字符串
        for (int i = 0; i < s.length(); i++) {
            //获取到每个字符
            //判断存入映射的字符是否已经包含
            char c= s.charAt(i);
            if (map.containsKey(c+"")){
                //获取上一次的这个键对应的值再加1
                map.put(c+"",map.get(""+c)+1);
            }else{//第一次存入不包含
                map.put(c+"",1);}
        }
        for (Map.Entry<String,Integer> entry: map.entrySet()
             ) {
            System.out.println(entry.getKey()+"="+entry.getValue());
        }
    }
}
  • 主要实现类:HashMap、Hashtable
  • HashMap

可以允许存储null值和null键,默认初始容量为16,默认扩容是增加一倍,如果指定初始容量,指定的值在2'n~2'(n+1),那么底层真实的容量就是2’n+1  异步式线程不安全集合

  • Hashtable

不允许存储null值和null键,默认初始容量是11,默认扩容是在原来的基础上增加一倍再加一 11---22+1----46+1 ,如果指定初始容量底层真实的初始容量就是多少。 同步式线程安全集合

映射是集合吗? 不是集合但是有联系, java集合类框架(Java Collections Framwork)-----集合、映射以及相关的操作类(Collection、Collections、Map、数组、操作数组类、Comparable接口、Iterator接口。。)

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值