Search code examples
guavamultiset

Guava: Access elements in TreeMultiset via position in expanded entrySet


Is there an efficient way to get the n upper entries from a sorted Multiset (TreeMultiset)?

To specify what I mean I post my inefficient solution:

public SortedMultiset<DataTuple> headMultiset(int upperBound, BoundType boundType){
    int i=0;
    DataTuple act= this.coreData.firstEntry().getElement();
    Iterator<DataTuple> itr = this.coreData.iterator();
    while(i<=upperBound){
        act = itr.next();
        i+=this.coreData.count(act);
    }
    return headMultiset(act, boundType);
}

In this example DataSet can be seen as Object and this.coreData is the underling TreeMultiset.

I'm really new to that topic, so all kinds of comments would be appreciated.


Solution

  • Actually the solution with the HashMap seems to have a acceptable performance. I built the hash map via:

    public NavigableMap<Integer, E> BuildHashMap (SortedMultiset<E> multiset){
        NavigableMap<Integer, E>  ret = new TreeMap<Integer, E>();
        int n = 0;
        for (Entry<E> e : multiset.entrySet()) {
            ret.put(n, e.getElement());
            n += e.getCount();
        }
        return ret;
    }
    

    and access it with .floorEntry(n).getValue().

    However elementSet().asList() is the function I'm actually looking for.