import java.util.*;
public class Test {
public static void main(String[] args) {
Map<Integer,String> map1=new HashMap();
Map<String,Integer> map2=new HashMap();
map1.put(2,"张三");
map1.put(1,"李四");
map1.put(3,"王二");
map2.put("张三",2);
map2.put("李四",3);
map2.put("王二",1);
sortByKey(map1);
sortByValue(map2);
}
public static void sortByKey(Map<Integer,String> map){
List<Map.Entry<Integer,String>> list=new ArrayList<Map.Entry<Integer,String>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer,String>>() {
@Override
public int compare(Map.Entry<Integer,String> o1, Map.Entry<Integer,String> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
for(Map.Entry entry : list){
System.out.println("key:"+entry.getKey() + "value:"+entry.getValue());
}
}
public static void sortByValue(Map<String,Integer> map){
List<Map.Entry<String,Integer>> list=new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
for(Map.Entry entry : list){
System.out.println("key:"+entry.getKey() + "value:"+entry.getValue());
}
}
}
网友评论