我正在查看一个冗余的字符串列表,例如
{ "One", "One", "One", "Two", "Three", "Three" }
什么是计算出现次数的最佳方法,然后创建一个非冗余字符串列表,按出现次数排序?
我想要的结果是这样的列表:
{ "One", "Three", "Two" }
最佳答案
您可以在这个关于 how to sort the map by its values 的问题的投票最多的答案中使用技巧.
这是一个示例实现(我已经向比较器添加了泛型):
- 将字符串/事件添加到 HashMap 中
- 将所有内容放入 TreeMap 中,并使用自定义比较器对值进行排序
- 将 key 放回列表中
public static void main(String[] args) {
String[] strings = {"One", "One", "One", "Two", "Three", "Three"};
//Count occurences
Map<String, Integer> map = new HashMap<String, Integer>();
for (String s : strings) {
if (map.containsKey(s)) {
map.put(s, map.get(s) + 1);
} else {
map.put(s, 1);
}
}
ValueComparator<String, Integer> comparator = new ValueComparator<String, Integer> (map);
Map<String, Integer> sortedMap = new TreeMap<String, Integer> (comparator);
sortedMap.putAll(map);
List<String> sortedList = new ArrayList<String> (sortedMap.keySet());
System.out.println(sortedMap);
System.out.println(sortedList);
}
static class ValueComparator<K, V extends Comparable<V>> implements Comparator<K> {
Map<K, V> map;
public ValueComparator(Map<K, V> base) {
this.map = base;
}
@Override
public int compare(K o1, K o2) {
return map.get(o2).compareTo(map.get(o1));
}
}
关于java - 计算 String 出现次数并按它们排序的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11504902/