public class Map1 { public static void main(String[] args) { Map<String,Integer> map1 = new HashMap<String,Integer>(); map1.put("a",1); map1.put("r",4); map1.put("q",8); map1.put("c",6); System.out.println(map1); //通过键值来删除键值对 map1.remove("r"); System.out.println(map1); //map1的长度 System.out.println(map1.size()); //判断当前的map集合是否包含指定key System.out.println(map1.containsKey("j")); //判断当前的map集合是否包含指定value System.out.println(map1.containsValue(4)); Set<String> map=map1.keySet();//获取map集合的key的集合 // map1.values();//获取集合的所有value for (String m: map){ System.out.println("key:"+ m+" value:"+map1.get(m)); System.out.println("===================="); } } }
输出结果:
{a=1, q=8, r=4, c=6}
{a=1, q=8, c=6}
3
false
false
key:a value:1
key:q value:8
key:c value:6
====================
TreeMap:
public class Test { public static void main(String[] args) { //TreeMap的自然排序是字典排序 Map<Integer,String> tree1 = new TreeMap<Integer,String>(); tree1.put(17, "a"); tree1.put(12, "ac"); tree1.put(16, "aw"); tree1.put(18, "art"); tree1.put(142, "aj"); System.out.println(tree1); } }
输出结果:
{12=ac, 16=aw, 17=a, 18=art, 142=aj}