Tin*_*iny 3 java sorting hashmap map
我正在尝试排序java.util.Map如下.
public final class SortMapByValue <K, V extends Comparable<? super V>> implements Comparator<Map.Entry<K, V>>
{
@Override
public int compare(Entry<K, V> o1, Entry<K, V> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValue(Map<K, V> unsortedMap)
{
List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(unsortedMap.entrySet());
Collections.sort(list); //Compiler error here.
Map<K, V> sortedMap = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}
Run Code Online (Sandbox Code Playgroud)
如代码中所述,它发出编译时错误,如下所示.
no suitable method found for sort(List<Entry<K,V>>)
method Collections.<T#1>sort(List<T#1>,Comparator<? super T#1>) is not applicable
(cannot instantiate from arguments because actual and formal argument lists differ in length)
method Collections.<T#2>sort(List<T#2>) is not applicable
(inferred type does not conform to declared bound(s)
inferred: Entry<K,V>
bound(s): Comparable<? super Entry<K,V>>)
where K,V,T#1,T#2 are type-variables:
K extends Object declared in method <K,V>sortMapByValue(Map<K,V>)
V extends Comparable<? super V> declared in method <K,V>sortMapByValue(Map<K,V>)
T#1 extends Object declared in method <T#1>sort(List<T#1>,Comparator<? super T#1>)
T#2 extends Comparable<? super T#2> declared in method <T#2>sort(List<T#2>)
Run Code Online (Sandbox Code Playgroud)
这也可以在以下方法中以下列方式完成sortMapByValue().
Collections.sort(list, new Comparator<Map.Entry<K, V>>()
{
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
Run Code Online (Sandbox Code Playgroud)
但相反,我想修复错误以遵循这种方式(避免这个匿名比较器).如何解决这个错误?
Map.Entry没有实现Comparable,所以Collections.sort(List<Entry>)无法知道如何对条目进行排序.所以你必须提供一个比较器.
但由于您SortMapByValue已经实现了Comparator接口,因此您只需使用该类的实例:
Collections.sort(list, new SortMapByValue<>());
Run Code Online (Sandbox Code Playgroud)
另请注意,使用Java 8可以显着减少代码的长度:
public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValue(Map<K, V> unsortedMap) {
return unsortedMap.entrySet().stream()
.sorted(comparing(Entry::getValue))
.collect(toMap(Entry::getKey, Entry::getValue, (e1,e2) -> e1, LinkedHashMap::new));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
809 次 |
| 最近记录: |