What's the preferred way to get an iterator that iterates over all elements
of an unsorted list, in sorted order? My approach was to create a copy of
the list, sort it and then return the sorted list's iterator.
This seems crude ... is it?
Cheers,
David
public Iterator getSortedIterator() {
List l = new ArrayList();
l.addAll(myCollection.values());
Collections.sort(l, new FooModelComparator());
return l.iterator();
}
privatestaticclass FooModelComparator implements Comparator {
publicint compare(Object o1, Object o2) {
Foo s1 = (Foo) o1;
Foo s2 = (Foo) o2;
return s1.getId().compareTo(s2.getId());
}
}
What's the preferred way to get an iterator that
iterates over all elements
of an unsorted list, in sorted order? My approach
was to create a copy of
the list, sort it and then return the sorted list's
iterator.
This seems crude ... is it?
No, I think it's about the best you could do algorithmically. Your code could be improved though:
public Iterator getSortedIterator() {
List l = new ArrayList(myCollection.values());
Collections.sort(l, new Comparator() {
publicint compare(Object o1, Object o2) {
Foo s1 = (Foo) o1;
Foo s2 = (Foo) o2;
return s1.getId().compareTo(s2.getId());
}});
return l.iterator();
}