【发布时间】:2014-01-14 03:10:07
【问题描述】:
我在java中做一些execrices,我必须从文件中读取单词,然后
把这个词放到 Map 类型的 Hashmap (word<String,Integer>) 中。一切都完成了。
下一组对(类型 java.util.Map.Entry),保存到 List(List<Entry<String,Integer>>),然后按 Collections.sort(List,Comparator) 对其进行排序。
但它不起作用,因为它说这种排序不合适而且我对这种排序没有太多经验,有人可以在这个当前的例子中帮助我吗? ...谢谢你的帮助。
代码中有一部分:
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();
}
【问题讨论】:
-
@brianRoach 谢谢你的时间,但我知道,有 java 文档和数百个例子。我正在寻找可以在此示例中进行解释的人,而不是发送链接。但也谢谢你。
-
您的代码不起作用/没有意义。为什么要创建一个您不使用的
slova类和一个您使用的slova变量?为什么你使用word1和其他人却没有定义它们? -
@nathanielwaisbrot 是 word1 的错误,意思是我会在 map 中放入一些在文本中出现频率的词,例如 slova.put("car",5) 。我会修理它。对于 slova 类,我正在使用 getValue() ...但是当然,我看到了许多比较器的示例,我不知道如何在我的示例中使用它,所以我尝试了一些,并且还有 slova 类。接下来要做什么才能使这个比较器起作用?谢谢...
-
你的代码还是很乱。我建议在尝试进一步学习之前与讲师交谈或阅读一些有关 Java 的介绍性文本。
标签: java dictionary collections comparator