Map 和S et 是 一种专门 用来进行搜索的 数据结构。 适合动态查找 。
一、Map(存储key-value)
Map
是一个接口类,该类没有继承自
Collection
,该类中存储的是
<K,V>
结构的键值对,并且
K
一定是唯一的,不
能重复
。

常用的方法:
1、map.put(K的类型 key, V的类型 value) 往里放元素
Map<String,Integer> map=new HashMap<>(); map.put("abc",3);//put是往里放元素 map.put("bit",2); map.put("hello",4); System.out.println(map);//会自动调用toString方法
注意:hashmap存储元素的时候,不是按照存储的顺序进行打印的。
存储的时候,是根据哈希函数来进行存储的。
Map<String, Integer> map = new HashMap<>(); map.put("abc", 3); map.put("bit", 2); map.put("bit", 4); System.out.println(map);
注意: 存储元素时,如果key相同,value值会被覆盖
2、V的类型 =map.get(key) 通过key值获取value值
int ret=map.get("abc");//ret为33、V的类型 =map.getOrDefault(key,没有key所对值时要返回的值)
map.getOrDefault("bit2",98);//找不到bit2,也就找不到对应的value,此时就返回设定的value值984、V的类型 =map.remove(key) 删除
Integer ret2=map.remove("bit");//删除值为bit的 System.out.println(ret2);//25、Set<key的类型> set=map.keySet() 返回所有 key 的不重复集合
因为Set这个集合当中存储的元素都是不重复的
Map<String, Integer> map = new HashMap<>(); map.put("abc", 3);//put是往里放元素4 map.put("bit", 2); map.put("hello", 4); Set<String> set=map.keySet();//此时就把所有key=放在了set里 System.out.println(set);//abc bit hello
6、Collection<V的类型> =map. values() 返回所有 value 的可重复集合
7、Set<Map.Entry<K的类型, V的类型>> =map.entrySet() 返回所有的 key-value 映射关系![]()
Map<String, Integer> map = new HashMap<>(); map.put("abc", 3); map.put("bit", 2); map.put("bit", 4);
本文详细介绍了Java中的Map与Set数据结构,包括Map的put、get、remove等方法,Set的add、remove等操作。还列举了多个实战题目,如统计数据出现次数、去重、查找重复数据等,展示了Map和Set在解决问题中的应用场景。



最低0.47元/天 解锁文章
1043

被折叠的 条评论
为什么被折叠?



