Map接口中常用的方法: V put(K key,V value) 向Map集合中添加键值对 V get(Object key) 通过key获取value void clear() 清空Map集合 boolean containsKey(Object key) 判断Map中是否包含某个key boolean containsValue(Object value) 判断Map中是否包含某个value boolean isEmpty() 判断Map集合中元素个数是否为0 V remove(Object key) 通过key删除键值对 int size() 获取Map集合键值对个数 Collection<V> values() 获取Map集合中所有value,返回一个Collection Set<K> keySet() 获取Map集合所有key(所有的键是一个set集合) Set<Map,Entry<K,V> entrySet() 将Map集合转换成Set集合
源码:
public class MapText { public static void main(String[] args) { Map<Integer,String> m1 = new HashMap<>(); m1.put(null,null); m1.put(null,"100"); //覆盖value为null System.out.println(m1.size()); System.out.println(m1.get(null)); m1.put(1,"黎明"); m1.put(2,"张学友"); m1.put(3,"刘德华"); m1.put(4,"郭富城"); String value = m1.get(1); System.out.println(m1.get(1)); //获取key为1的value System.out.println(m1.get(2)); System.out.println(m1.get(3)); System.out.println(m1.get(4)); m1.clear(); //清空m1集合 m1.put(8,"薛之谦"); m1.put(9,"易烊千玺"); m1.put(10,"杨千嬅"); m1.put(11,"陈奕迅"); System.out.println(m1.containsKey(1)); //判断m1中是否包含key为1的键值对; System.out.println(m1.containsKey(8)); //判断m1中是否包含key为8的键值对; System.out.println(m1.containsValue("薛之谦")); //判断m1中是否包含value为薛之谦的键值对 System.out.println(m1.size()); //m1集合的键值对个数 Collection<String> c1 = m1.values(); //获取m1集合中的value元素,collection类型 Iterator<String> it1 = c1.iterator(); while (it1.hasNext()){ System.out.println(it1.next()); } Set<Integer> key1 = m1.keySet(); //获取Map集合所有key(所有的键是一个set集合) Iterator<Integer> it2 = key1.iterator(); while (it2.hasNext()){ Integer i1 = it2.next(); System.out.print(i1+"="+m1.get(i1)+"\t"); } System.out.println(); System.out.println("=========通过key获取value========="); for (Integer key : key1){ System.out.print(key+"="+m1.get(key)+"\t"); } System.out.println(); System.out.println("===========Map.Entry<K,V>==========="); Set<Map.Entry<Integer,String>> sets = m1.entrySet(); //调用entrySet将Map转换成Set集合,Map.Entry<Object,Object>类型 Iterator<Map.Entry<Integer,String>> it3 = sets.iterator(); //生成迭代器遍历转换后的Set集合 while (it3.hasNext()){ Map.Entry<Integer,String> sets2 = it3.next(); //通过迭代器获取set集合中的所有对象,Map.Entry<Object,Object>类型 Integer key2 = sets2.getKey(); //通过getKey方法获取对象key值 String value2 = sets2.getValue(); //通过getValue方法获取对象key值 System.out.print(key2+"="+value2+"\t"); } System.out.println(); System.out.println("===========foreach============"); for (Map.Entry<Integer,String> setn : sets){ Integer key3 = setn.getKey(); String value3 = setn.getValue(); System.out.print(key3+"="+value3+"\t"); } } }
学习笔记