一、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<String,Object> entry: map.entrySet()){
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
Iterator<Map.Entry<String,Object>> it = map.entrySet().iterator();
while (it.hasNext()){
Map.Entry<String,Object> 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<Map.Entry<String,Object>>() {
@Override
public int compare(Map.Entry<String,Object> o1, Map.Entry<String,Object> 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