Java中的集合(Map)

Map:

将键映射到值的对象。

  • 一个映射不能包含重复的键;

  • 每个键最多只能映射到一个值。

  • 实现类: HashMap, TreeMap, Hashtable,

  • 从以下版本开始:1.2

  • 注意

  • 1:当有重复的键的时候,后面的值会将前面的值覆盖

  • 2:可以添加null键null值,但是只能添加一对

  • 3:值可以重复

  • 4:map集合主要是和键有关系,只要找到键,就能根据键找到值

  • Map集合其实就是由Set和List构成的
    key是Set集合 不能有重复
    Value是List集合 可以有重复

    集合常用方法
    添加 put(k,v)
    删除 remove(k)
    清空 clear();
    修改 ???
    查询 get(k) 根据键查找值
    长度:size();
    判断
    containsKey 判断是否包含指定的键
    containsValue 判断是否包含指定的值
    isEmpty 判断集合是否为空
    遍历

public static void main(String[] args) {
		//1:创建Map集合
		HashMap<String, String> map = new HashMap<>();
		//2:给集合添加键值对
		map.put("超", "俪");
		map.put("明", "颖");
		map.put("章", "琍");
		map.put("章", "姚");
		map.put("强", "蓉");
		map.put("哲", "蓉");
		
		map.put(null, null);
		map.put(null, null);
		System.out.println(map);
		
		//2:删除键值对  根据键删除键值对
		map.remove("章");
		System.out.println("删除后:"+map);
		//3:清空键值对
		//map.clear();
		//System.out.println(map);
		//4:根据键查找值  如果此映射不包含该键的映射关系,则返回 null。
		System.out.println(map.get("超1"));
		//5:获取键值对的对数
		System.out.println(map.size());
		//6:判断是否包含指定的键
		System.out.println(map.containsKey("超"));
		//7:判断是否包含指定的值
		System.out.println(map.containsValue("俪"));
		//8  isEmpty  判断集合是否为空
		System.out.println(map.isEmpty());
		//9 返回所有的键的set集合
		/*System.out.println("---------------------");
		Set<String> set = map.keySet();
		for (String s : set) {
			System.out.println(s);
		}
		System.out.println("---------------------");
		//10 返回所有的值的Collection集合
		Collection<String> coll = map.values();
		for (String s : coll) {
			System.out.println(s);
		}*/
		System.out.println("---------------------");
		//11 遍历键值对1
		//11.1 现获取所有的键
		Set<String> set = map.keySet();
		//11.2 遍历所有的键
		for (String key : set) {
			//11.3 遍历一个键,然后在根据键获取值
			String value = map.get(key);
			System.out.println(key+":"+value);
		}
		System.out.println("---------------------");
		//12 遍历键值对2
		Set<Map.Entry<String, String>> entrySet = map.entrySet();
		for(Map.Entry<String, String> s:entrySet){
			System.out.println(s.getKey()+":"+s.getValue());
		}
		
		
		  	}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张子又

感觉有用就打赏点吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值