我正在使用此代码对单词和整数对进行排序,按整数对对进行排序(降序)
对元组进行排序后,如何仅将字符串值保存在 String [] 数组中?
我在这里找到了代码,因为我是新来的,所以我无法在同一页面上发表评论。(@Elliott Frisch)
public Tuple(int count, String word) {
this.count = count;
this.word = word;
}
@Override
public int compareTo(Tuple o) {
return new Integer(this.count).compareTo(o.count);
}
public String toString() {
return word + " " + count;
}
}
public static void main(String[] args) {
String[] words = { "the", "he", "he", "he", "he", "he", "he", "he",
"he", "the", "the", "with", "with", "with", "with", "with",
"with", "with" };
// find frequencies
Arrays.sort(words);
Map<String, Integer> map = new HashMap<String, Integer>();
for (String s : words) {
if (map.containsKey(s)) {
map.put(s, map.get(s) + 1);
} else {
map.put(s, 1);
}
}
List<Tuple> al = new ArrayList<Tuple>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
al.add(new Tuple(entry.getValue(), entry.getKey()));
}
Collections.sort(al);
System.out.println(al);
}
白衣非少年
温温酱
相关分类