根据ids的相关列表重新排序集合 [英] Reordering a collection according to a related list of ids
问题描述
我有一个具有 id 属性的对象集合(无序),以及 ids 的(有序)列表。 ID列表未排序。我想在我的集合中创建一个对象列表,根据ID列表排序。
I have a Collection (unordered) of objects with an id property, and an (ordered) List of ids. The id list is not sorted. I'd like to create a List of the objects in my Collection, ordered according to the List of ids.
我没有在Guava中看到这个方法, Apache Commons - 但这正是我要找的。一个具有良好实现的库函数。
I didn't see a method for this in Guava or Apache Commons - but that's exactly what I'm looking for. A library function with a good implementation.
推荐答案
听起来你的id列表有自己的顺序;
It sounds like your id list has its own order; you're not just using the natural order, right?
这里是Guava的解决方案:
Here's the Guava solution:
Ordering.explicit(idList)
// constructs a "fluent Comparator" that compares elements in the
// explicitly specified order
.onResultOf(new Function<MyObject, Id>() {
public Id apply(MyObject o) { return o.getId(); }
}) // make this a Comparator<MyObject> that compares on IDs
.sortedCopy(myObjects); // get the sorted copy of the collection
就是这样。没有什么。
That's it. Nothing to it. (Disclosure: I contribute to Guava.)
或者,如果你知道ID是唯一的,它可能只是说
Alternately, if you know IDs are unique, it might just say
Map<Id, MyObject> objectsById =
Maps.uniqueIndex(myObjects, GET_ID_FUNCTION); // defined elsewhere
List<MyObject> sortedObjects = Lists.newArrayList();
for (Id id : sortedIds)
sortedObjects.add(objectsById.get(id));
这篇关于根据ids的相关列表重新排序集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!