KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > management > stats > TopN


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.management.stats;
5
6 import java.util.Collections JavaDoc;
7 import java.util.Comparator JavaDoc;
8 import java.util.Iterator JavaDoc;
9 import java.util.SortedSet JavaDoc;
10 import java.util.TreeSet JavaDoc;
11
12 /**
13  * Keeps track of the top <strong>N</strong> entries of all those sumbitted according to their natural order, or as
14  * defined by the passed in {@link Comparator} if the second constructor is used. <strong>The comparator should order
15  * the elements from lowest to highest, otherwise you will wind up </strong>
16  */

17 public final class TopN {
18
19   private final SortedSet JavaDoc data;
20   private final int N;
21
22   /**
23    * Creates a top {@link #N} list according to a natural ordering, if you have a custom object you will be adding use
24    * {@link #TopN(Comparator, int)} instead.
25    */

26   public TopN(final int N) {
27     this(null, N);
28   }
29
30   /**
31    * Creates a top {@link N} list according to {@link comparator}.
32    */

33   public TopN(final Comparator JavaDoc comparator, final int N) {
34     data = new TreeSet JavaDoc(comparator != null ? new Comparator JavaDoc() {
35       public int compare(Object JavaDoc obj, Object JavaDoc obj1) {
36         return -comparator.compare(obj, obj1);
37       }
38     } : Collections.reverseOrder());
39     this.N = N;
40   }
41
42   /**
43    * @param object the object added to the top N list in order, if it qualifies according to the comparator
44    */

45   public void evaluate(final Object JavaDoc object) {
46     synchronized (data) {
47       data.add(object);
48       while (data.size() > N) {
49         data.remove(data.last());
50       }
51     }
52   }
53
54   /**
55    * @return a read-only {@link Iterator} of the "top" {@link #N} elements, in descending order -- that is, the
56    * "biggest" one is first.
57    */

58   public Iterator JavaDoc iterator() {
59     synchronized (data) {
60       return Collections.unmodifiableSortedSet(data).iterator();
61     }
62   }
63
64 }
65
Popular Tags