根据出现的频率排列列表的元素(具有重复元素)

Raj*_*pta 4 java collections

根据列表中出现的频率排列列表元素(具有重复元素)的好方法.

我需要使用列表中前5个经常出现的项目.

我正在考虑使用HashMap通过每次元素出现时递增相应的计数器来计算元素的频率,然后进行5次HashMap迭代以找到最高频率.每次迭代的元素.

Jig*_*shi 5

这种方法怎么样?

维护一个持有计数的地图

public static Map  <Foo,Integer>;
Run Code Online (Sandbox Code Playgroud)
class Foo implements Comparator<Foo>{  
      private Bar element;


      public int compare(Foo f1, Foo f2){
       return SomeClass.map.get(f1) - SomeClass.map.get(f2);
      }

    }
Run Code Online (Sandbox Code Playgroud)

只需更新地图即可更新地图list.

使用强制包装对List的访问addFooToList(),removeFooFromList()并在那里封装地图更新逻辑.


Sea*_*oyd 5

您可以使用番石榴Multiset并按频率订购


关于表现.当然,这取决于你有多少不同的值,但这个测试代码在我的机器上花了大约一秒钟.而且我认为这对10 M物品来说足够合理:

Multiset<Integer> set = HashMultiset.create();
int amount = 10000000;
Random random = new Random();
for (int i = 0; i < amount; i++) {
    set.add(Integer.valueOf(random.nextInt(255)));
}
TreeSet<Entry<Integer>> sortedEntries = Sets.newTreeSet(
        new Comparator<Entry<Integer>>() {
    public int compare(Entry<Integer> a, Entry<Integer> b) {
        return Ints.compare(a.getCount(), b.getCount());
    }
});
Iterables.addAll(sortedEntries, set.entrySet());
for (Entry<Integer> entry : Iterables.limit(sortedEntries, 5)) {
    System.out.println(entry.getElement());
}
Run Code Online (Sandbox Code Playgroud)