Arrays.sort引发编译时错误“派生自Comparator ..的匿名类." [英] Arrays.sort throws compile-time error 'Anonymous class derived from Comparator..'
本文介绍了Arrays.sort引发编译时错误“派生自Comparator ..的匿名类."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
错误:
必须声明从Comparator派生的匿名类抽象或实现抽象方法compare(T,T).
Anonymous class derived from Comparator must either be declared Abstract or implement abstract method compare(T,T).
我想根据地图中的频率对数组进行排序.
I want to sort the Array based on frequency in the map.
HashMap<Integer,Integer> freq = new HashMap<>();
for(int a:arr)
{
freq.putIfAbsent(a,freq.getOrDefault(a,0)+1);
}
Arrays.sort(arr,new Comparator<>(){
public int compare(int a,int b)
{
if(freq.get(b)!=freq.get(a))
return freq.get(b)-freq.get(a);
else
return a-b;
}
});
我在这里想念什么?
推荐答案
假设您有 Integer []
之类的
Integer[] arr = { 10, 2, 30, 4 };
您可以按照以下步骤进行操作:
you can do it as follows:
Arrays.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
if (freq.get(b) != freq.get(a))
return Integer.compare(freq.get(b), freq.get(a));
else
return a.compareTo(b);
}
});
如果您有 int []
这样的
int[] arr = { 10, 2, 30, 4 };
将其转换为 Integer []
as
Integer[] arr1 = Arrays.stream(arr).boxed().toArray(Integer[]::new);
,然后将 arr1
排序为
Arrays.sort(arr1, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
if (freq.get(b) != freq.get(a))
return Integer.compare(freq.get(b), freq.get(a));
else
return a.compareTo(b);
}
});
这篇关于Arrays.sort引发编译时错误“派生自Comparator ..的匿名类."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文