Reordering a collection according to a related list of ids

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

    Create a class that implements Comparable. In that class, do the sorting according to your ordered list of ids. Then define a TreeSet based on the Comparable class. A greatly simplified example is shown below.

    e.g.

    public class MyObject implements Comparable {
      private Integer id;
    
      // a map of IDs to how they are ordered.
      private static Map idOrder = null;
    
      public MyObject(Integer id) {
          setId(id);
    
          if (idOrder == null) {
               idOrder = new HashMap();
               idOrder.put(17, 1);
               idOrder.put(27, 2);
               idOrder.put(12, 3);
               idOrder.put(14, 4);
          }
      }
    
      public int getId() {
          return (this.id);
      }
    
      public void setId(int id) {
          this.id = id;
      }
    
      public int compareTo(MyObject anotherThing) {
        return (idOrder.get(this.getId()).compareTo(idOrder.get(anotherThing.getId()))); 
      }
    }
    

    Then, define and populate your set like so:

    private Set mySet = new TreeSet;
    mySet.add(new MyObject(12));
    mySet.add(new MyObject(17));
    

    When you do a mySet.add(), it will automatically sort according to your MySort class. If you iterate over the resulting TreeSet, the "17" entry will come before the "12" entry.

提交回复
热议问题