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

前端 未结 4 689
时光说笑
时光说笑 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:58

    An Implementation using ForwardingMultiSet :

    (EntryComp from seanizer's answer)

    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 class FreqSortMultiSet extends ForwardingMultiset {
        Multiset delegate;
        EntryComp comp;
    
        public FreqSortMultiSet(Multiset delegate, boolean ascending) {
            this.delegate = delegate;
            if (ascending)
                this.comp = EntryComp.ASCENDING;
            else
                this.comp = EntryComp.DESCENDING;
        }
    
        @Override
        protected Multiset delegate() {
            return delegate;
        }
    
        @Override
        public Set> entrySet() {
            TreeSet> sortedEntrySet = new TreeSet>(comp);
            sortedEntrySet.addAll(delegate.entrySet());
            return sortedEntrySet;
        }
    
        @Override
        public Set elementSet() {
            Set sortedEntrySet = new LinkedHashSet();
            for (Entry en : entrySet())
                sortedEntrySet.add(en.getElement());
            return sortedEntrySet;
        }
    
        public static  FreqSortMultiSet create(boolean ascending) {
            return new FreqSortMultiSet(HashMultiset. create(), ascending);
        }
    
        /*
         * For Testing
         * public static void main(String[] args) {
            Multiset s = FreqSortMultiSet.create(false);
            s.add("Hello");
            s.add("Hello");
            s.setCount("World", 3);
            s.setCount("Bye", 5);
            System.out.println(s.entrySet());
        }*/
    
    }
    

提交回复
热议问题