1 4 package com.tc.management.stats; 5 6 import java.util.Collections ; 7 import java.util.Comparator ; 8 import java.util.Iterator ; 9 import java.util.SortedSet ; 10 import java.util.TreeSet ; 11 12 17 public final class TopN { 18 19 private final SortedSet data; 20 private final int N; 21 22 26 public TopN(final int N) { 27 this(null, N); 28 } 29 30 33 public TopN(final Comparator comparator, final int N) { 34 data = new TreeSet (comparator != null ? new Comparator () { 35 public int compare(Object obj, Object obj1) { 36 return -comparator.compare(obj, obj1); 37 } 38 } : Collections.reverseOrder()); 39 this.N = N; 40 } 41 42 45 public void evaluate(final Object object) { 46 synchronized (data) { 47 data.add(object); 48 while (data.size() > N) { 49 data.remove(data.last()); 50 } 51 } 52 } 53 54 58 public Iterator iterator() { 59 synchronized (data) { 60 return Collections.unmodifiableSortedSet(data).iterator(); 61 } 62 } 63 64 } 65 | Popular Tags |