我正在尝试按整数排序数组List<Entry<String, Integer>>
。在开始时,我的代码将文本文件读取为字符串。然后是字符串拆分为单词并保存到字符串数组,所有单词都更改为小写。然后使用哈希映射保存单词和他们的计数。然后将哈希映射转换为数组列表。现在我需要使用比较器按整数对此列表进行排序。我尝试了很多方法,但没有结果。这是我的代码,对不起我的英文:
package test2;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
public class Test2 {
public static void main(String[] args) throws Exception {
try {
File file = new File("filee.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder build = new StringBuilder(150000);
String line;
while ((line = reader.readLine()) != null) {
build.append(line);
}
reader.close();
String text = "";
text = build.toString();
String[] words;
words = text.split("[,; .\\-\\\"]");
String text0 = "";
for (String str0 : words) {
text0 = text0 + str0 + " ";
}
for (int i = 0; i < words.length; i++) {
words[i] = words[i].toLowerCase();
}
Map<String, Integer> count = new HashMap<String, Integer>();
for (int i = 0; i < words.length; i++) {
if (count.containsKey(words[i])) {
count.put(words[i], count.get(words[i]) + 1);
} else {
count.put(words[i], 1);
}
}
for (Map.Entry<String, Integer> entry : count.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(count.entrySet());
//Here I need to sort list using Collections.sort(list, Comparator)
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getKey() + " : " + list.get(i).getValue());
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
答案 0 :(得分:1)
试试这个:
Collections.sort(count.entrySet(), new Comparator<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> x, Entry<String, Integer> y) {
return x.getValue() - y.getValue();
}
});
答案 1 :(得分:1)
尝试:
@Override
public int compare(Entry<String, Integer> arg0, Entry<String, Integer> arg1) {
if (arg0 == null && arg1 != null){
return -1;
}else if (arg0 != null && arg1 == null){
return 1;
}else if (arg0 == null && arg1 == null){
return 0;
}
if (arg0.getValue() == null && arg1.getValue() != null){
return -1;
}else if (arg0.getValue() != null && arg1.getValue() == null){
return 1;
}else if (arg0.getValue() == null && arg1.getValue() == null){
return 0;
}
return arg0.getValue().compareTo(arg1.getValue());
}