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 crea
It sounds like your id list has its own order; you're not just using the natural order, right?
Here's the Guava solution:
Ordering.explicit(idList)
// constructs a "fluent Comparator" that compares elements in the
// explicitly specified order
.onResultOf(new Function() {
public Id apply(MyObject o) { return o.getId(); }
}) // make this a Comparator that compares on IDs
.sortedCopy(myObjects); // get the sorted copy of the collection
That's it. Nothing to it. (Disclosure: I contribute to Guava.)
Alternately, if you know IDs are unique, it might just say
Map objectsById =
Maps.uniqueIndex(myObjects, GET_ID_FUNCTION); // defined elsewhere
List sortedObjects = Lists.newArrayList();
for (Id id : sortedIds)
sortedObjects.add(objectsById.get(id));