Design Pattern 总结
public interface Iterator {
/**
* @return True if the there is a next element
*/
boolean hasNext();
/**
* @return next Highest number and removes the items from the stream.
*/
int getNextHighestNumber();
}
class MergedIterator {
List<Iterator> _listIters;
PriorityQueue<Pair<?,?>> maxHeap;
/**
* Construct MergedIterator.
* @param iterators list of iterator
*/
MergedIterator(List<Iterator> iterators) {
if (iterators == null || iterators.size() <= 0) throw new Exception("");
_listIters = iterators;
maxHeap = new PriorityQueue<Pair<Int, Iterator>, >(new MyCompartor());
for (Iterator iter: _listIters) {
if (iter.hasNext())
maxHeap.insert(new Pair(iter.getNextHighestNumber(), iter));
}
}
/**
* @return true if there is a next element.
*/
boolean hasNext() {
return maxHeap.size() > 0;
}
/**
* @return next max element across all the iterators.
*/
int getNextHighestNumber() {
if (!hasNext()) throw new Exception("Empty");
Pair pair = maxHeap.pop();
int num = pair.getFirst();
Iterator iter = pair.getSecond();
if (iter.hasNext())
maxHeap.insert(new Pair(iter.getNextHighestNumber(), iter));
return num;
}
}
Read full article from Design Pattern 总结