java-Map相关方法

一、map转化list、

    HashMap map = new HashMap();
    map.put("1","一");
    map.put("2","二");
    map.put("3","三");
    //        List ketSet = new ArrayList(map.keySet()); 
    //        List ketSet = new ArrayList(map.values());
    List ketSet = new LinkedList(map.entrySet());
    利用构造方法的参数转化为list

二、遍历map

    System.out.println(list);

    for(Map.Entry entry: map.entrySet()){
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }
    Iterator>  it = map.entrySet().iterator();
    while (it.hasNext()){
        Map.Entry rn  =   it.next();
        System.out.println(rn.getKey());
        System.out.println(rn.getValue());
    }

三、根据map的key排序

    List list = new ArrayList(map.entrySet());
    System.out.println(list);
    Collections.sort(list, new Comparator>() {

        @Override
        public int compare(Map.Entry o1, Map.Entry o2) {
            return Integer.valueOf(o2.getKey()) - Integer.valueOf(o1.getKey()) ;
        }
    });

    System.out.println(list);

输出:
排序之前:[1=一, 2=二, 3=三]
排序之后:[3=三, 2=二, 1=一]

四、不可修改map

    Map unmap ;
    unmap = Collections.unmodifiableMap(map);
    unmap.put("4","四");

会报错:
Exception in thread "main" java.lang.UnsupportedOperationException

你可能感兴趣的:(java-Map相关方法)