Reordering a collection according to a related list of ids

后端 未结 6 1473
一向
一向 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:22

    If your unordered input is no more specific than Collection and your List of ids is in an arbitrary order (not decreasing numerically or something like that), your simplest and quite performant approach is probably this. The cost is linear, O(m+n) where m is the number of ids in your initially sorted list and n is the number of values to sort.

    Map keyed = new HashMap();
    for (ValueType value : unsortedCollection) {
        keyed.put(value.getId(), value);
    }
    
    List sorted = new ArrayList();
    for (IDType id : sortedIds) {
        ValueType value = keyed.get(id);
        if (value != null) {
            sorted.add(value);
        }
    }
    

提交回复
热议问题