1.Map接口
map接口是一个双列集合,每个元素有一个键值 对 Map
public interface Map<K, V> { }
2.HashMap实现类
Map 实现类为 HashMap,HashMap 实例化,添加,判断,清空,删除,替换
2.1HashMap基本使用
//实例化Map对象 Map<String,Book> map = new HashMap<>(); //添加元素,添加元素时,如果Key值存在,则覆盖元素 map.put("b02",book); //判断有没有Key map.containsKey(); //判断有没有Value map.containsValue(); //获取指定元素 get(String key) System.out.println(map.get("b01"));
2.2HashMap遍历KeySet Values
Map<String,String> map = new HashMap<>(); map.put("bj","北京"); map.put("tj","天津"); map.put("hn","河南"); map.put("sh","上海"); //第一种遍历方式 keySet()方法返回Set集合 Set<String> keys = map.keySet(); for(String k : keys){ //System.out.println(k); System.out.printf("map[\"%s\"] = %s%n",k,map.get(k)); } //第二种遍历方式 values() 返回Collection<String> 集合 Collection<String> values = map.values(); for(String v : values){ System.out.println(v); } //第三种遍历方式 entrySet() 返回一个Set<Map.Entry<String,String>> 集合 Set<Map.Entry<String, String>> entries = map.entrySet(); for(Map.Entry<String,String> e : entries){ //System.out.println(e); System.out.println(e.getKey()); System.out.println(e.getValue()); } //第四种遍历方式 使用迭代器接口Iterator 接口 Iterator<String> iterator = map.values().iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); }
3.TreeMap实现类
是一个有序的key-value集合,它是通过红黑树实现的。该映射根据其键的自然顺序进行排序,或 者根据创建映射时提供的 Comparator 进行排序,具体取决于使用的构造方法。
TreeMap<String, Integer> tm = new TreeMap<>(); TreeMap<String, Integer> tm = new TreeMap<>((a, b) -> a.compareTo(b)); //降序 //TreeMap<Double, String> t2 = new TreeMap<>((a, b) -> a < b ? 1 : -1); //升序 //TreeMap<Double, String> t2 = new TreeMap<>((a, b) -> a > b ? 1 : -1); TreeMap<Student, String> t3 = new TreeMap<>((a,b)->a.getId()- b.getId());