Have you ever had the problem of finding sublists inside a sorted List. It's one of those requirements that's rare enough not to get covered much yet irritating to have to code on those occasions when you need it. Here's one approach. It's assumed that the List will be sorted, else the whole thing doesn't make much sense anyway. The source is HERE.
import java.util.*;
/**
* Acts as an Iterator to retrieve sublists of a sorted List
* of Comparable
*/
public class ComparableSublistRetriever<T extends Comparable<T>>
implements Iterator<List<T>> {
private List<T> delegate;
private T previous;
private T current;
private int index;
public ComparableSublistRetriever(List<T> items) {
delegate = new ArrayList<T>(items);
Collections.sort(delegate);
}
@Override
public boolean hasNext() {
return index < delegate.size();
}
@Override
public List<T> next() {
List<T> sublist = new ArrayList<T>();
T current = delegate.get(index++);
sublist.add(current);
previous = current;
while(index < delegate.size() && (current = delegate.get(index)).equals(previous)) {
sublist.add(current);
previous = current;
index++;
}
return sublist;
}
@Override
public void remove() {
throw new RuntimeException("remove() as yet unimplemented - do your worst!");
}
public static void main(String[] args) {
// (For testing) Retrieve the sublists from the app arguments
ComparableSublistRetriever<String> r = new ComparableSublistRetriever<String>(Arrays.asList(args));
while (r.hasNext()) {
System.out.println(r.next());
}
}
}
/**
* Acts as an Iterator to retrieve sublists of a sorted List
* of Comparable
*/
public class ComparableSublistRetriever<T extends Comparable<T>>
implements Iterator<List<T>> {
private List<T> delegate;
private T previous;
private T current;
private int index;
public ComparableSublistRetriever(List<T> items) {
delegate = new ArrayList<T>(items);
Collections.sort(delegate);
}
@Override
public boolean hasNext() {
return index < delegate.size();
}
@Override
public List<T> next() {
List<T> sublist = new ArrayList<T>();
T current = delegate.get(index++);
sublist.add(current);
previous = current;
while(index < delegate.size() && (current = delegate.get(index)).equals(previous)) {
sublist.add(current);
previous = current;
index++;
}
return sublist;
}
@Override
public void remove() {
throw new RuntimeException("remove() as yet unimplemented - do your worst!");
}
public static void main(String[] args) {
// (For testing) Retrieve the sublists from the app arguments
ComparableSublistRetriever<String> r = new ComparableSublistRetriever<String>(Arrays.asList(args));
while (r.hasNext()) {
System.out.println(r.next());
}
}
}