In my application I need to keep resulting collection in the same order as requested (user sends a list of what he wants and it is desirable to answer him in the same order).
Data, what I will send to user is generated by underlying layers, and they neither know the correct order, nor generate ordered result. So I have to order it myself.
My approach is following, but I think that it's not necessary to implement it, because there should be some standard way. So, what would you recommend?
public class KeepOrder {
/**
* Knows how to extract A from B.
*
* @param <A>
* @param <B>
*/
public interface Extractor<A, B> {
A extract(B from);
}
@SuppressWarnings("serial")
public static <T, F> Collection<T> keepOrder(final Collection<T> data, final Collection<F> order,
final Extractor<F, T> extractor) {
final Comparator<T> tComparator = new Comparator<T>() {
@Override
public int compare(final T o1, final T o2) {
final F field1 = extractor.extract(o1);
final F field2 = extractor.extract(o2);
for (final F currentField : order) {
if (currentField.equals(field1) && currentField.equals(field2)) {
return 0;
}
if (currentField.equals(field1)) {
return -1;
}
if (currentField.equals(field2)) {
return 1;
}
}
return 0;
}
};
return new TreeSet<T>(tComparator) {
{
addAll(data);
}
};
}
}
If the order is important in your collection, you should restrict yourself to List
s.
From the documentation of List
:
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
精彩评论