java Map 按value值排序和按key值排序

来源:互联网 发布:tensorflow 版本 编辑:程序博客网 时间:2024/06/15 00:49
public class Test {    public static void main(String[] args) throws ClassNotFoundException {        // TODO Auto-generated method stub        Map<String, Integer> map = new HashMap<String, Integer>();        map.put("d", 2);        map.put("c", 1);        map.put("b", 4);        map.put("a", 3);        map.put("e", 5);        List<Map.Entry<String, Integer>> list =            new ArrayList<Map.Entry<String, Integer>>(map.entrySet());        for (int i = 0; i < list.size(); i++) {            String id = list.get(i).toString();            System.out.println(id);        }        System.out.println("-------------按value排序----------------------------");        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {               public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {                      return (o1.getValue() - o2.getValue());             }        });         for (int i = 0; i < list.size(); i++) {            String id = list.get(i).toString();            System.out.println(id);        }        System.out.println("--------------按key排序-----------------------------");        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {               public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {                      return (o1.getKey()).toString().compareTo(o2.getKey());            }        });        for (int i = 0; i < list.size(); i++) {            String id = list.get(i).toString();            System.out.println(id);        }    }}result:d=2e=5b=4c=1a=3-------------按value排序----------------------------c=1d=2a=3b=4e=5--------------按key排序-----------------------------a=3b=4c=1d=2e=5
0 0
原创粉丝点击