思路:
将出现过的数以及次数放进Map中,转成List,用Comparator就可以排序了。参数中o2-o1,与排序规则相反,为降序
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<n;i++) {
int temp = sc.nextInt();
if(map.containsKey(temp)) {
map.replace(temp,map.get(temp)+1);
}else {
map.put(temp, 1);
}
}
//需要按照map的value排序。先转成List,再sort
List<Map.Entry<Integer, Integer>> list= new ArrayList<Map.Entry<Integer, Integer>>(map.entrySet());
list.sort(new Comparator<Map.Entry<Integer, Integer>>() {
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
for (Map.Entry<Integer, Integer> entry : list) {
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}