开发者

copy order between collections [duplicate]

This question already has answers here: Reordering a collection according to a related list of ids (6 answers) 开发者_如何学编程 Closed 3 years ago.

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 Lists.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜