Java字典。util。地图进入和收集。排序(列表、比较器)
我正在用java执行一些操作,我必须从文件中读取单词,然后
将这些单词放入映射类型Hashmap(word<String,Integer>
)。一切都完成了
下一组对(键入java.util.Map.Entry),保存到列表(List<Entry<String,Integer>>
)中,然后按集合对其排序。排序(列表、比较器)。
但是它不起作用,因为它说排序不合适,而且我对这种排序没有太多的经验,有人能在当前的示例中帮助我如何。。。谢谢你的帮助
代码中有一部分:
public static void Reader(){
class Word{
private String key;
private int value;
public int getValue(){
return value;
}
public void setValue(){
value=this.value;
}
public String getKey(){
return key;
}
public void setKey(){
key=this.key;
}
public Word(String key,Integer value){
this.key= key;
this.value = value;
}
public Word(){
}
}
Map<String, Integer> wordsmap = new HashMap<String, Integer>();
wordsmap.put("car",2); // wordsmap.put(word as key,frequency as value)
wordsmap.put("bike",6);
wordsmap.put("like",1);
List<Entry<String,Integer>> words = new ArrayList<>(wordsmap.entrySet());
Collections.sort(words,new Comparator<Word>(){
public int compare(Word o1,Word o2){
return o1.getValue() - o2.getValue();
}
});
}
public static void main(String[] args) {
Reader();
}
# 1 楼答案
将
List<Entry<String, Integer>>
与Comparator<Entry<String, Integer>>
排序:您还没有指出要如何比较条目:我已经比较了键,但是您可以根据自己的喜好计算比较
Java 8更新,使用lambda而不是匿名类: