Simplest way to iterate through a Multiset in the order of element frequency?

前端 未结 4 686
时光说笑
时光说笑 2020-11-29 08:01

Consider this example which prints out some device type stats. (\"DeviceType\" is an enum with a dozenish values.)

Multiset histogram = get         


        
4条回答
  •  遥遥无期
    2020-11-29 08:42

    Here's a method that returns a List of entries, sorted by frequency (UPDATE: used a flag to toggle ascending / descending order and used Guava's favorite toy: the Enum Singleton Pattern, as found in Effective Java, Item 3 ):

    private enum EntryComp implements Comparator>{
        DESCENDING{
            @Override
            public int compare(final Entry a, final Entry b){
                return Ints.compare(b.getCount(), a.getCount());
            }
        },
        ASCENDING{
            @Override
            public int compare(final Entry a, final Entry b){
                return Ints.compare(a.getCount(), b.getCount());
            }
        },
    }
    
    public static  List> getEntriesSortedByFrequency(
        final Multiset ms, final boolean ascending){
        final List> entryList = Lists.newArrayList(ms.entrySet());
        Collections.sort(entryList, ascending
            ? EntryComp.ASCENDING
            : EntryComp.DESCENDING);
        return entryList;
    }
    

    Test code:

    final Multiset ms =
        HashMultiset.create(Arrays.asList(
            "One",
            "Two", "Two",
            "Three", "Three", "Three",
            "Four", "Four", "Four", "Four"
        ));
    
    System.out.println("ascending:");
    for(final Entry entry : getEntriesSortedByFrequency(ms, true)){
        System.out.println(MessageFormat.format("{0} ({1})",
            entry.getElement(), entry.getCount()));
    }
    
    System.out.println("descending:");
    for(final Entry entry : getEntriesSortedByFrequency(ms, false)){
        System.out.println(MessageFormat.format("{0} ({1})",
            entry.getElement(), entry.getCount()));
    }
    

    Output:

    ascending:
    One (1)
    Two (2)
    Three (3)
    Four (4)
    descending:
    Four (4)
    Three (3)
    Two (2)
    One (1)

提交回复
热议问题