英文:
Error while sorting using Collections sort
问题
在运行下面的代码时,我收到了一个错误。我需要关于如何解决这个错误的建议。
Map<String, String> map = new HashMap<String, String>();
map.put("test", "milan");
map.put("joo", "arsenal");
map.put("keer", "manu");
List list = new LinkedList(map.entrySet());
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return (((Comparable) ((Map.Entry) (o1)).getValue()).compareTo((Map.Entry) (o2)));
}
});
错误: 异常在线程“main”中发生: java.lang.ClassCastException: java.util.HashMap$Node无法转换为java.lang.String
英文:
When running the below code I get an error. I need suggestion on how to solve the error.
Map<String, String> map = new HashMap<String, String>();
map.put("test", "milan");
map.put("joo", "arsenal");
map.put("keer", "manu");
List list = new LinkedList(map.entrySet());
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return (((Comparable) ((Map.Entry) (o1)).getValue()).compareTo((Map.Entry) (o2)));
}
});
Error: Exception in thread "main" java.lang.ClassCastException: java.util.HashMap$Node cannot be cast to java.lang.String
答案1
得分: 2
在你的比较器返回行中,应该是:
return ((Comparable) ((Map.Entry) (o1)).getValue()).compareTo((Comparable) ((Map.Entry) (o2)).getValue());
原因是你忘记从 o2 中获取值。
英文:
In your Comparator return line, it should be:
return ((Comparable) ((Map.Entry) (o1)).getValue()).compareTo((Comparable) ((Map.Entry) (o2)).getValue());
The reason is you forgot to get Value from o2
答案2
得分: 2
你正在比较 String
与 Map.Entry
在 comapre
中使用 ((Map.Entry) (o2)).getValue())
,
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return (((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue()));
}
});
你可以使你的代码更易读,如下所示,
List<Map.Entry<String, String>> list = new LinkedList(map.entrySet());
Collections.sort(list, Comparator.comparing(Map.Entry::getValue));
英文:
You are comparing String
with Map.Entry
in comapre
Use ((Map.Entry) (o2)).getValue())
,
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return (((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue()));
}
});
You can make your code more readable as,
List<Map.Entry<String, String>> list = new LinkedList(map.entrySet());
Collections.sort(list, Comparator.comparing(Map.Entry::getValue));
答案3
得分: 0
替代Collections.sort()
,你应该使用list.sort()
来对列表进行排序。
List<Map.Entry<String, String>> list = new LinkedList<>(map.entrySet());
list.sort(Map.Entry.comparingByValue());
英文:
Instead of Collections.sort()
you should use list.sort()
for sorting a list.
List<Map.Entry<String, String>> list = new LinkedList<>(map.entrySet());
list.sort(Map.Entry.comparingByValue());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论