1. 双列集合
双列集合也是用于存储数据的,但是与单列集合不同的是,双列集合是以key=value
的形式存在的。每个部分包含两部分key和value。
2. 特点
- Map键是无序、不可重复和无索引的。
- Map值是不做要求的。
- Map存相同键的值,后者会覆盖前者
- Map的键和值都可以是null
3. 双列集合体系
- HashMap:键无序、不重复和无索引,值不做要求。(哈希表加值元素)
- LinkedHashMap:键有序、不重复和无索引,值不做要求。(哈希表加双向链表)
- TreeMap:键按照规则排序、不重复和无索引,值不做要求。(红黑树)
4. 常用API
Map常用API:
方法名称 | 说明 |
---|---|
V put(K key,V value) | 添加元素 |
V remove(Object key) | 根据键删除键值对元素 |
void clear() | 移除所有的键值对元素 |
boolean containsKey(Object key) | 判断集合是否包含指定的键 |
boolean containsValue(Object value) | 判断集合是否包含指定的值 |
boolean isEmpty() | 判断集合是否为空 |
int size() | 集合的长度,也就是集合中键值对的个数 |
5. 格式
HashMap<键类型, 值类型> 变量名 = new HashMap<>()
6. Map集合遍历
6.1 键找值的方法
选获得Map的键,然后通过键获得对应的值。
public class HashMapTest1 {
public static void main(String[] args) {
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "张三");
hashMap.put(2, "李四");
hashMap.put(3, "王二");
Set<Integer> integers = hashMap.keySet();
for (Integer integer : integers) {
System.out.println("{key=" + integer + ", value=" + hashMap.get(integer) + "}");
}
}
}
6.2 迭代器方式
把键值对看成一个对象,获得这个对象集合进行遍历
public class HashMapTest2 {
public static void main(String[] args) {
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "张三");
hashMap.put(2, "李四");
hashMap.put(3, "王二");
Set<Map.Entry<Integer, String>> entries = hashMap.entrySet();
for (Map.Entry<Integer, String> entry : entries) {
System.out.println("{key=" + entry.getKey() + ", value=" + entry.getValue() + "}");
}
}
}
6.3 Lambda表达式
public class HashMapTest3 {
public static void main(String[] args) {
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "张三");
hashMap.put(2, "李四");
hashMap.put(3, "王二");
// 传统匿名内部类
hashMap.forEach(new BiConsumer<Integer, String>() {
@Override
public void accept(Integer integer, String s) {
System.out.println("{key=" + integer + ", value=" + s + "}");
}
});
// Lambda表达式
hashMap.forEach((i, s) -> System.out.println("{key=" + i + ", value=" + s + "}"));
}
}
本章结束,用于个人学习和小白入门,大佬勿喷!希望大家多多点赞收藏支撑支撑!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。