数组元素出现次数降序排列,如果次数相同,按元素大小升序排列。数组元素不限定类型,可以是整数,也可以是字符串
思路:
1.用map记录数组元素和出现次数,treemap不能用,如果元素是null,treemap put报错。
2.比较使用Comparator或者Comparable。(默认升序)
比如:
1 public static void main(String[]args){ 2 String[] arr = {"aaa", "bbb", "ccc", "ddd", "ddd", "aaa"}; 3 Map<String, Integer> map = new HashMap(); 4 //计算出现次数 5 for (String str :arr) { 6 Integer count = map.get(str); 7 map.put(str, count == null ? 1 : count + 1); 8 } 9 10 List<Map.Entry<String, Integer>> entryList = new ArrayList<>(); 11 entryList.addAll(map.entrySet()); 12 //次数,大小排序 13 Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() { 14 @Override 15 public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { 16 if (o1.getValue() == o2.getValue()) { 17 return o1.getKey().compareTo(o2.getKey()); 18 } 19 return o2.getValue().compareTo(o1.getValue()); 20 } 21 }); 22 //打印 23 for (Map.Entry<String, Integer> entry:entryList ){ 24 System.out.println(entry.getKey() + ": " + entry.getValue()); 25 } 26 27 }