The Java Embedded Aggregator Class TopAggregate

TopAggregate implements the aggregation returning the top N values.

For an overview see page Java Aggregator Class

Class Definition

 
    public static class TopAggregate implements Aggregate<Comparable>
    {
        public void initialize(Comparable val) 
        {
            max[0] = val;
            used = 1;
        }
 
        public void accumulate(Comparable val) 
        {
            int l = 0, n = used, r = n;
            while (l < r) 
            {
                int m = (l + r) >>> 1;
                if (val.compareTo(max[m]) < 0) 
                 {
                    l = m + 1;
                } else {
                    r = m;
                }
            }
         
            if (used < max.length) 
            {
                System.arraycopy(max, r, max, r+1, used-r);
                max[r] = val;
                used += 1;
            } else if (r < used) {
                System.arraycopy(max, r, max, r+1, used-r-1);
                max[r] = val;
            }
        }
 
        /**
        * Result of aggregation
        * @return array with top N values. If there are less than N object in aggregated set, 
        * then size of result array may be smaller than N
        */
        public Object result() 
        {
            if (used < max.length) 
            {
                Comparable[] res = new Comparable[used];
                System.arraycopy(max, 0, res, 0, used);
                return res;
            }
            return max;
        }
 
        public void merge(Aggregate<Comparable> other) 
        {
            for (Comparable obj : (Comparable[])other.result()) 
            {
                accumulate(obj);
            }
        }
 
        /**
        * Aggregate constructor
        * @param n top N
        */
        public TopAggregate(int n) 
        {
            max = new Comparable[n];
            used = 0;
        }
 
        Comparable[] max;
        int used;
    }