# Java笔试题一道

`#!/usr/bin/env pythonarr = ["a", "b", "d", "d", "a", "d", "a", "e", "d", "c"]d = {}for element in arr:    d[element] = arr.count(element)print sorted(d.iteritems(), key = lambda d : d[1], reverse = True)`

d.iteritems()这个参数是字典d的键值对的元组集合

key=这个参数是指排序的对象，这里用了lambda表达式，d[1]表示用字典的value来进行排序

reverse=这个参数True表示降序，False表示升序，默认为False，题目要求从多到少，所以是降序

`package Love;import java.util.*;/** * Hello world! * */public class App{    public static class ValueComparator implements Comparator<Map.Entry<String, Integer>> {        @Override        public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {            return o2.getValue() - o1.getValue();        }    }        public static void main( String[] args )    {        String[] arr = {"a", "b", "d", "d", "a", "d", "a", "e", "d", "c"};        Map<String, Integer> map = new HashMap<String, Integer>();        for (String myKey : arr) {            if (map.containsKey(myKey)) {                map.put(myKey, map.get(myKey) + 1);            }            else {                map.put(myKey, 1);            }        }        List<Map.Entry<String, Integer>> myList = new ArrayList<Map.Entry<String, Integer>>();        myList.addAll(map.entrySet());        ValueComparator vc = new ValueComparator();        Collections.sort(myList, vc);        for (Map.Entry<String, Integer> m : myList) {            System.out.println(m.getKey() + "=>" + m.getValue());        }    }}`

`package Love;import java.util.*;/** * Hello world! * */public class App{    public static void main( String[] args )    {        String[] arr = {"a", "b", "d", "d", "a", "d", "a", "e", "d", "c"};        Map<String, Integer> map = new HashMap<String, Integer>();        for (String myKey : arr) {            if (map.containsKey(myKey)) {                map.put(myKey, map.get(myKey) + 1);            }            else {                map.put(myKey, 1);            }        }        List<Map.Entry<String, Integer>> myList = new ArrayList<Map.Entry<String, Integer>>();        myList.addAll(map.entrySet());        Collections.sort(myList, new Comparator<Map.Entry<String, Integer>>() {            @Override            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {                return o2.getValue() - o1.getValue();            }        });        Iterator<Map.Entry<String, Integer>> iter = myList.iterator();        while (iter.hasNext()) {            System.out.println(iter.next());        }    }}`

`package java.util;public interface Comparator<T>{    int compare(T o1, T o2);    boolean equals(Object obj);}`

compare是比较o1和o2的大小：

o1 < o2，返回负数

o1 = o2，返回0

o1 > o2，返回正数

Collections提供以下方法对List进行排序操作
void reverse(List list),反转
void shuffle(List list),随机排序
void sort(List list),按自然排序的升序排序
void sort(List list, Comparator c);定制排序，由Comparator控制排序逻辑
void swap(List list, int i , int j),交换两个索引位置的元素
void rotate(List list, int distance),旋转。当distance为正数时，将list后distance个元素整体移到前面。