ccf之数字排序(基于Map集合value从大到小排序)

时间:2022-03-30 21:32:03

一直都不知道Map集合要如何根据value值来排序,尤其是当集合的key值要用来和输入值进行比较来决定value值的情况,在这种情况下就不好采用Set集合,不然要遍历整个集合里的元素看哪个对象的变量是否和要比较的数相等,我说得不清楚,具体情况可以参见这道题的情形

当然这道题也可以直接用数组,就是运算量感觉会大一点,但是基于那个知识点我一直不清楚所以执拗的用了这个方法

方法是从网上看的,大致思路是先创建Map集合来存储对应的键值对,再自定义一个比较器,这个比较器是对Map集合的value值进行比较,如何做到这一点呢,创建一个list集合,并用map集合生成一个map.entry(),并将这个entry传入到list集合中对其进行初始化,然后利用Collections.sort(list,new Comparator()),到这里,我们就可以自定义自己的比较器了,因为有Map.Entry(),所以我们可以很方便地取到Map集合中的键和值进行比较了。

好的,看代码:

package Online_pra;

import java.util.*;
import java.util.Map.Entry;

public class CCF1503_2{
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
TreeMap<Integer,Integer>tm=new TreeMap<Integer,Integer>();
for(int i=0;i<n;i++){
int num=scan.nextInt();
if(tm.containsKey(num)) {
int m=tm.get(num);
m++;
tm.put(num, m);
}
else tm.put(num, 1);
}
List<Map.Entry<Integer, Integer>> list=new ArrayList<Map.Entry<Integer,Integer>>(tm.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>(){

//public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
//if(o2.getValue().compareTo(o1.getValue())>0)
//return 1;
//else if(o2.getValue().compareTo(o1.getValue())==0){
//if(o2.getKey().compareTo(o1.getValue())<0)
//return 1;
//else
//return -1;
//}
//else
// return -1;
//}
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2)
{

if(o2.getValue().compareTo(o1.getValue())>0){//按value递减顺序排序
return 1;
}
else if(o2.getValue().compareTo(o1.getValue())==0){
if(o2.getKey().compareTo(o1.getKey())<0)//如果value相同输出key小的
return 1;
else return -1;
}
else{
return -1;
}

}

});
for(Map.Entry<Integer, Integer> me:list) {
System.out.println(me.getKey()+" "+me.getValue());
}
}
}
如上,但是一直没找到注释掉的那段代码与下面那段代码之间有什么区别,哪位大神指出来一下喽。