在集合之间复制顺序
在我的应用程序中,我需要按照请求的顺序保留结果集合(用户发送他想要的列表,并且最好以相同的顺序回答他)。
数据,我将发送给用户的数据是由底层生成的,它们既不知道正确的顺序,也不生成有序的结果。所以我必须自己订购。
我的方法如下,但我认为没有必要实现它,因为应该有一些标准的方法。那么,你会推荐什么?
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);
}
};
}
}
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);
}
};
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果顺序在您的集合中很重要,您应该将自己限制在
List
中。来自
List
的文档< /a>:If the order is important in your collection, you should restrict yourself to
List
s.From the documentation of
List
: