一、介绍
Java中的Map是一种键值对的集合数据类型,用于存储无序的、不重复的键值对。它提供了快速的查找和访问功能,可以根据键来获取值。
常见的Map实现类有:HashMap、TreeMap、LinkedHashMap等。
二、HashMap
HashMap是Java中的一种键值对集合,它允许存储不重复的键和对应的值,使用哈希表(数组+链表/红黑树)实现。HashMap中的键和值都可以为null。
下面是HashMap的一些常用方法:
- put(K key, V value):添加键值对。
- get(Object key):根据键获取值。
- remove(Object key):删除指定键的键值对。
- containsKey(Object key):判断是否包含指定的键。
- containsValue(Object value):判断是否包含指定的值。
- size():返回集合中键值对的个数。
- clear():清空集合中所有的键值对。
使用示例:
public class Demo1_Map {
/*
* hashset底层依赖hashmap
* hashmap是双列集合
* 添加功能:map.put("张三",23)
* 删除功能:map.remove("张三");返回对应的值
* 是否包含:map.containsKey("李四"),map.containsValue(24)
* 返回所有值:map.values();
* 集合大小:map.size()
* */
public static void main(String[] args){
test2();
}
public static void test1(){
Map<String,Integer> map = new HashMap<>();
map.put("张三",23);//相同的键不存储,值覆盖
map.put("李四",24);
// map.remove("张三");
Collection<Integer> c = map.values();
System.out.println(c);
System.out.println(map);
System.out.println(map.containsKey("李四"));
System.out.println(map.containsValue(24));
//获取所有的键,遍历map集合
Set<String> keySet = map.keySet();//拿到所有的键
for (String s:keySet) {
Integer i= map.get(s);
System.out.println(i);
}
}
//map集合第二种迭代,根据键值对对象,获取键和值
public static void test2(){
Map<String,Integer> map = new HashMap<>();
map.put("张三",23);//相同的键不存储,值覆盖
map.put("李四",24);
//map.entry说明entry是map的内部接口,将键和值封装成对象,并存储在set集合中
// Set<Map.Entry<String,Integer>> entryset = map.entrySet();
// //获取每一个对象
// Iterator<Map.Entry<String,Integer>> it = entryset.iterator();
// while (it.hasNext()){
// //获取每一个entry对象
// Map.Entry<String,Integer> en = it.next();
// System.out.println(en.getKey()+en.getValue());
// }
for (Map.Entry<String,Integer> en:map.entrySet()) {
System.out.println(en.getKey()+en.getValue());
}
}
}
三、TreeMap
TreeMap是Java中的一种有序键值对集合,它基于红黑树实现,可以保证元素按照键的顺序进行排序。TreeMap允许null值但不允许null键。
下面是TreeMap的一些常用方法:
- put(K key, V value):添加键值对。
- get(Object key):根据键获取值。
- remove(Object key):删除指定键的键值对。
- containsKey(Object key):判断是否包含指定的键。
- containsValue(Object value):判断是否包含指定的值。
- size():返回集合中键值对的个数。
- clear():清空集合中所有的键值对。
- firstKey():返回第一个键。
- lastKey():返回最后一个键。
- subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive):返回部分子Map。
使用示例:
TreeMap<String, Integer> map = new TreeMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
int value = map.get("apple");
System.out.println(value); // 输出1
map.remove("orange");
if (map.containsKey("banana")) {
System.out.println("Map中包含键为'banana'的元素");
}
String firstKey = map.firstKey();
String lastKey = map.lastKey();
System.out.println("第一个键:" + firstKey + ",最后一个键:" + lastKey);
// 返回子Map
SortedMap<String, Integer> subMap = map.subMap("apple", true, "banana", false);
System.out.println(subMap); // 输出{"apple"=1}
存储自定义对象需要重写comparator接口
//treemap存储自定义对象student和string案例,需要重写comparator接口
public class Demo4_TreeMap {
public static void main(String[] args){
TreeMap<Student,String> tm = new TreeMap<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int n = o1.getAge() - o2.getAge();
return n==0?o1.getName().compareTo(o2.getName()):n;
}
});
tm.put(new Student("张三啊",23),"北京");
tm.put(new Student("张三啊",23),"上海");
tm.put(new Student("李四",24),"广州");
tm.put(new Student("王五",25),"深圳");
System.out.println(tm);
}
}
需要注意的是,TreeMap是有序的,但它并不是线程安全的。如果多个线程同时修改同一个TreeMap实例,可能会导致数据不一致或者抛出ConcurrentModificationException异常。如果需要在多线程环境中使用TreeMap,可以考虑使用ConcurrentSkipListMap等线程安全的实现类。
四、LinkedHashMap
LinkedHashMap是HashMap的一个子类,它可以维护插入元素时的顺序,也可以通过访问顺序来迭代。
可以通过以下两种方式来创建LinkedHashMap。
Map<String, String> linkedHashMap1 = new LinkedHashMap<>();
Map<String, String> linkedHashMap2 = new LinkedHashMap<>(16, 0.75f, true);
第一个方式创建LinkedHashMap时,它的顺序是不确定的。第二个方式创建LinkedHashMap时,它可以按照访问顺序来迭代。其中16是初始化容量,0.75f是负载因子,true表示采用访问顺序。如果不需要按照访问顺序来迭代,则可以将最后一个参数设置为false。
简单使用:
public class Demo3_linkedHashMap {
public static void main(String[] args){
LinkedHashMap<String,Integer> lhm = new LinkedHashMap<>();
lhm.put("张三",23);
lhm.put("李四",24);
lhm.put("王五",25);
System.out.println(lhm);
}
}