import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Main{
public static void main(String [] args) throws InterruptedException {
int [] data = {1,1,2,3,2,2,2,3,3};
System.out.println(get(data));
}
public static List<Integer> get(int[] data) {
//result集合保存最终结果
List<Integer> result = new ArrayList<Integer>();
//map集合统计数组数字频率
HashMap<Integer,Integer> h = new HashMap<Integer,Integer>();
for(int i =0;i<data.length;i++) {
if(h.get(data[i]) == null) {
h.put(data[i], 1);
}else {
h.put(data[i], h.get(data[i])+1);
}
}
Set<Entry<Integer,Integer>> keySet = h.entrySet();
List<Map.Entry<Integer, Integer>> infoIds = new ArrayList<>(keySet);
//按list集合按值大小降序排序
Collections.sort(infoIds,new Comparator<Map.Entry<Integer, Integer>>(){
@Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
return o2.getValue()-o1.getValue();
}
});
//得到最终结果
for(int i = 0;i<infoIds.size();i++) {
for(int j = 0;j<infoIds.get(i).getValue();j++) {
Integer id = infoIds.get(i).getKey();
result.add(id);
}
}
return result;
}
}
将一个数组数字按频率降序排序
最新推荐文章于 2024-05-12 20:01:39 发布