MultiSet+TreeMap实现次数统计

备注:需要引入guava的jar包
要求:
MultiSet+TreeMap实现次数统计_第1张图片
实现:

import java.util.Iterator;
import java.util.TreeMap;

import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;


public class SortString {
    public static void main(String[] args) {
        int[] array = {1,2,2,5,5,5,3,3,3,3};
        // MultiSet用于统计次数
        Multiset multiset = HashMultiset.create();
        for (int i = 0; i < array.length; i++) {
            multiset.add(array[i]);
        }
        // TreeMap用于排序
        TreeMap treeMap = new TreeMap();
        for (Integer integer : multiset.elementSet()) {
            treeMap.put(multiset.count(integer), integer);
        }
        Iterator iterator = treeMap.descendingKeySet().iterator();
        while (iterator.hasNext()){
            Integer integer = iterator.next();
            System.out.println(treeMap.get(integer) + " 出现 " + integer + "次");
        }
    }
}

你可能感兴趣的:(Java,次数统计,MultiSet,TreeMap)