Reordering a collection according to a related list of ids

后端 未结 6 1472
一向
一向 2021-01-16 06:52

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

6条回答
  •  生来不讨喜
    2021-01-16 07:13

    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));
    

提交回复
热议问题