22
33import java .util .*;
44
5+ /**
6+ * Given a list of Iterators that produce an non-decreasing sequence, the CollatingIterator
7+ * can produce a collated, non-decreasing sequence without dropping any values from the
8+ * underling iterators.
9+ *
10+ * @param <E> Type - could be a primitive or a custom class
11+ */
512public class CollatingIterator <E > implements Iterator <E >
613{
7- private PriorityQueue <E > pq ;
8- private List <Iterator <E >> allIterators ;
9- private Map <E , Iterator <E >> waitingValues ;
10-
14+ /**
15+ * Constructs an empty instance.
16+ */
1117 public CollatingIterator () {
1218 pq = new PriorityQueue <E >();
13- allIterators = new ArrayList <Iterator < E > >();
14- waitingValues = new HashMap <E , Iterator < E > >();
19+ allIterators = new ArrayList <>();
20+ waitingValues = new HashMap <>();
1521 }
1622
23+ /**
24+ * Constructs an empty instance with a Comparator
25+ * @param comparator Comparator instance to compare elements.
26+ */
1727 public CollatingIterator (Comparator <? super E > comparator ) {
1828 pq = new PriorityQueue <E >(comparator );
19- allIterators = new ArrayList <Iterator < E > >();
20- waitingValues = new HashMap <E , Iterator < E > >();
29+ allIterators = new ArrayList <>();
30+ waitingValues = new HashMap <>();
2131 }
2232
33+ /**
34+ * Adds the given iterator to an internal list of iterators.
35+ * @param it Iterator instance to add to the list.
36+ */
2337 public void addIterator (Iterator <E > it ) {
2438 allIterators .add (it );
2539 }
@@ -59,33 +73,7 @@ private void pullFrom(Iterator<E> it) {
5973 }
6074 }
6175
62- public static void main (String [] args ) {
63- CollatingIterator <Integer > ci = new CollatingIterator <>();
64- ci .addIterator (new RandomIncreasingIterator ());
65- ci .addIterator (new RandomIncreasingIterator ());
66- ci .addIterator (new RandomIncreasingIterator ());
67- for (int i = 0 ; i < 10 ; i ++)
68- System .out .println (ci .next ());
69- }
70-
71- private static class RandomIncreasingIterator implements Iterator <Integer > {
72- public RandomIncreasingIterator () {}
73- private Integer lastValue = null ;
74- @ Override
75- public boolean hasNext () {
76- return true ;
77- }
78- @ Override
79- public Integer next () {
80- Integer value = (int ) (Math .random () * 10.0 );
81- //System.out.println("value="+value+", lastValue="+lastValue);
82- if (lastValue == null ) {
83- lastValue = value ;
84- return value ;
85- } else {
86- lastValue = lastValue + value ;
87- return lastValue ;
88- }
89- }
90- }
91- }
76+ private PriorityQueue <E > pq ;
77+ private List <Iterator <E >> allIterators ;
78+ private Map <E , Iterator <E >> waitingValues ;
79+ }
0 commit comments