我有一个集合,一个对象(无序) 的ID 属性,一个(有序)列表 的ID 。 ID列表未排序 。我想在我的收藏夹中创建一个对象列表,并根据ID列表进行排序。
我在Guava或Apache Commons中没有看到用于此目的的方法-但这正是我想要的。具有良好实现的库函数。
听起来您的ID列表有自己的顺序;您不仅在使用自然顺序,对吗?
这是番石榴解决方案:
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
而已。没什么 (公开:我为番石榴做出了贡献。)
或者,如果您知道ID是唯一的,则可能会说
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));