From f3d35142afc51c167c655170360cf2f98ff7c7cb Mon Sep 17 00:00:00 2001 From: ray Date: Wed, 17 Dec 2003 21:58:06 +0000 Subject: [PATCH] A convenience class that lets you iterator over a non-sorted collection or iterator in a sorted manner. git-svn-id: https://samskivert.googlecode.com/svn/trunk@1358 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- .../com/samskivert/util/SortedIterator.java | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 projects/samskivert/src/java/com/samskivert/util/SortedIterator.java diff --git a/projects/samskivert/src/java/com/samskivert/util/SortedIterator.java b/projects/samskivert/src/java/com/samskivert/util/SortedIterator.java new file mode 100644 index 00000000..8ad707d6 --- /dev/null +++ b/projects/samskivert/src/java/com/samskivert/util/SortedIterator.java @@ -0,0 +1,78 @@ +// +// $Id: SortedIterator.java,v 1.1 2003/12/17 21:58:06 ray Exp $ + +package com.samskivert.util; + +import java.util.Collection; +import java.util.Comparator; +import java.util.Iterator; + +/** + * An iterator that returns the elements from another iterator into + * some sorted order. + */ +public class SortedIterator implements Iterator +{ + /** + * Construct a sorted iterator that iterates through the specified + * elements in natural order. + */ + public SortedIterator (Iterator itr) + { + this(itr, Comparators.COMPARABLE); + } + + /** + * Construct a sorted iterator that iterates through the specified + * elements in the order according to the specified comparator. + */ + public SortedIterator (Iterator itr, Comparator comparator) + { + SortableArrayList list = new SortableArrayList(); + while (itr.hasNext()) { + list.insertSorted(itr.next(), comparator); + } + _itr = list.iterator(); + } + + /** + * Construct a sorted iterator that iterates through the specified + * collection in natural order. + */ + public SortedIterator (Collection c) + { + this(c.iterator()); + } + + /** + * Construct a sorted iterator that iterates through the specified + * collection in the order according to the specified comparator. + */ + public SortedIterator (Collection c, Comparator comparator) + { + this(c.iterator(), comparator); + } + + // documentation inherited from interface Iterator + public boolean hasNext () + { + return _itr.hasNext(); + } + + // documentation inherited from interface Iterator + public Object next () + { + return _itr.next(); + } + + // documentation inherited from interface Iterator + public void remove () + { + // sadly, we cannot + throw new UnsupportedOperationException( + "Cannot remove from a SortedIterator"); + } + + /** The iterator we are a wrapper around. */ + protected Iterator _itr; +}