听起来您的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 elsewhereList<MyObject> sortedObjects = Lists.newArrayList();for (Id id : sortedIds) sortedObjects.add(objectsById.get(id));



