Map集合
来源:互联网 发布:快速背单词软件 编辑:程序博客网 时间:2024/06/04 23:24
Map:
一次添加一对元素,(Collection)一次添加一个元素。
Map也称双列集合,Collection集合称为单列集合。
其实map集合中存储的就是键值对。
map集合中必须保证健的唯一性。
常用方法
1.添加
value put(key,value)
返回一个前一个和key关联的值。如果没有返回null.
2.删除
void clear()
清空map集合。
value remove(key);
根据制定的key删除制定的键值对
3.判断
boolean containsKey(key);
boolean containsValue(value);
boolean isEmpty()
4.获取
value get(key)
通过健获取值,没有该key返回null,也可以通过返回null是否包含指定健
int size()
获取键值对的个数。
取出map中的所有元素
1、取出map中的所有元素的原理
通过keySet方法获取map中所在的Set集合,
在通过Set的迭代器获取到每一个键
在对每一个键获取其对应的值即可。
代码演示:
public class MapDemo { public static void main(String[] args) { Map<Integer,String> map=new HashMap<Integer,String>(); method_2(map); } public static void method_2(Map<Integer,String> map) { //添加元素 map.put(1, "xiaohong"); map.put(6,"xiaobai"); map.put(9,"xiaohua"); Set <Integer>keySet=map.keySet(); Iterator<Integer> it=keySet.iterator(); while(it.hasNext()){ System.out.println(map.get(it.next())); } }
2、通过Map转换成set就可以迭代
找到另一个方法。entrySet
该方法将键和值得映射关系作为对象存储到了Ser集合中,而这个映射关系就是Map.Entry类型。
public static void method_3(Map<Integer,String> map) { //添加元素 map.put(1, "xiaohong"); map.put(6,"xiaobai"); map.put(9,"xiaohua"); Set<Map.Entry<Integer, String>> entrySet =map.entrySet(); Iterator<Map.Entry< Integer, String>> it=entrySet.iterator(); while(it.hasNext()){ Map.Entry<Integer, String> msg=it.next(); System.out.println(msg.getKey()+"::::"+msg.getValue()); } }
3、如果想单纯的获得键所对应的值,则不用那么麻烦。
使用Collection value()方法即可。
public static void method_3(Map<Integer,String> map) { //添加元素 map.put(1, "xiaohong"); map.put(6,"xiaobai"); map.put(9,"xiaohua"); Collection coll=map.values(); Iterator<String> it=coll.iterator(); while(it.hasNext()) { System.out.println(it.next()); } }
Map下常用的子类:
|—Hashtable:内部数据结构是:哈希表,同步。不允许null作为键,不允许null作为值
|—Propertites:用来存储键值对型的配置文件信息,可以和I/O技术相结合。
|—Hashmap:内部数据结构是:哈希表,不同步。允许null作为键,允许null作为值
|—TreeMap:内部数据结构:是二叉树,不同步。可以对Map集合中的键进行排序。
- Map 集合
- Map集合
- Map集合
- map集合
- Map集合
- map集合
- Map集合
- Map集合
- Map集合
- Map集合
- Map集合
- map集合
- Map集合
- Map集合
- Map集合
- Map集合
- Map集合
- Map集合
- Linux命令
- Spring 过源码
- Ubuntu 10.04下安装fcitx输入法
- dubbo 的线程和连接模型 (长连接复用的两种形式)
- JavaScript Window
- Map集合
- ASPEN Aspenone V8.0化工流程模拟软件送8G\
- 动态增加div,实现div之间的切换,不刷新页面
- 已知两个链表head1 和head2 各自有序,请把它们合并成一个链表依然有序。
- Android状态栏微技巧,带你真正理解沉浸式模式
- 内省
- Spring boot(二)
- scala基础4⃣️集合
- 稳定排序:如果Ai = Aj,Ai原来在位置前,排序后Ai还是要在Aj位置前