首页 > 编程语言 > 详细

数组元素出现次数降序排列,如果次数相同,按元素大小升序排列。数组元素不限定类型,可以是整数,也可以是字符串

时间:2020-03-18 16:26:30      阅读:53      评论:0      收藏:0      [点我收藏+]

思路:

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 HashedMap();
 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     }

 

数组元素出现次数降序排列,如果次数相同,按元素大小升序排列。数组元素不限定类型,可以是整数,也可以是字符串

原文:https://www.cnblogs.com/ivy-xu/p/12517396.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!