计算String出现并按其排序的简单方法 [英] Simple way to count occurrences of String and sort by them

查看:81
本文介绍了计算String出现并按其排序的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看一个多余的字符串列表,例如

I am looking at a redundant list of Strings, e.g.

{ "One", "One", "One", "Two", "Three", "Three" }

计算出现次数的最佳方法是什么,然后创建一个字符串的非冗余列表,并按出现次数进行排序?

What is the best way to count the occurrences, then create a non-redundant list of the strings, sorted by the number of occurrences?

我想要的结果是一个像这样的列表:

The result I want is a List like this:

{ "One", "Three", "Two" }

推荐答案

您可以在有关这是一个示例实现(我向比较器添加了泛型):

Here is an example implementation (I have added generics to the comparator):

  • 您将字符串/事件添加到哈希图中
  • 使用自定义比较器对TreeMap中的所有内容进行排序,这些比较器对值进行排序
  • 将密钥放回列表中
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));
    }
}

这篇关于计算String出现并按其排序的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆