在Java中,你如何排序的基础上另外一个列表? [英] In Java how do you sort one list based on another?
问题描述
我见过类同这一个其他几个问题,但我还没有真正能够找到任何解决我的问题。
我的使用情况是这样的:用户有最初的项目(listA的)的列表。他们重新排列项目,并希望坚持的顺序(数组listB),但由于限制,我无法坚持在后端的顺序,所以我后,我检索排序为listA。
所以基本上,我有2个的ArrayList(为listA和数组listB)。一个具有特定次序的列表应该是(数组listB),而另一个具有项目(listA的)的列表。我想根据数组listB排序为listA。
Collections.sort(数组listB,新的比较<项目>(){
公众诠释比较(左项目,项目右){
返回Integer.compare(listA.indexOf(左),listA.indexOf(右));
}
});
这是非常低效的,虽然,你应该创建一个地图<项目,整数方式>
从为listA来查找项目的位置更快
番石榴有一个现成的使用比较做这件事:<一href=\"http://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/Ordering.html#explicit(java.util.List)\"相对=nofollow> Ordering.explicit()
I've seen several other questions similiar to this one but I haven't really been able to find anything that resolves my problem.
My use case is this: user has a list of items initially (listA). They reorder the items and want to persist that order (listB), however, due to restrictions I'm unable persist the order on the backend so I have to sort listA after I retrieve it.
So basically, I have 2 ArrayLists (listA and listB). One with the specific order the lists should be in (listB) and the other has the list of items (listA). I want to sort listA based on listB.
Collections.sort(listB, new Comparator<Item>() {
public int compare(Item left, Item right) {
return Integer.compare(listA.indexOf(left), listA.indexOf(right));
}
});
This is quite inefficient, though, and you should probably create a Map<Item, Integer>
from listA to lookup the positions of the items faster.
Guava has a ready-to-use comparator for doing that: Ordering.explicit()
这篇关于在Java中,你如何排序的基础上另外一个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!