2 Replies Latest reply: Feb 4, 2013 3:06 AM by Asrivast-Oracle RSS

    Collections.sort() on complex Object using custom Comparator

    Asrivast-Oracle
      Hi All,
      We have a Set<CompositeObject> with entries of a complex Object and before I could process each entry in a certain sequence based on one of keys in this complex object. The CompositeObject has two methods getFirst() and getSecond(). The first attribute is a String but the getSecond() returns a Collections.singletonMap (index, <SomePayload>); I need to sort the Collection based on the 'index'. What I have is something similar:
      <pre>
      public void process (Set set) {
      List sortedList = new ArrayList(set);
      Collections.sort(sortedList, new Comparator() {
      @Override
      public int compare (Object o1, Object o2) {
      int c1 = (Integer) ((Map) (((CompositeObject) o1).getSecondary()).keySet().iterator().next());
      int c2 = (Integer) ((Map) (((CompositeObject) o2).getSecondary()).keySet().iterator().next());

      return Integer.compare(c1, c2);
      }
      </pre>

      But when I do iterator() on sortedList it is not returning the expected sorting. What am I missing?