Sorting

1 minute read

Soring based on simple fields are easy to do when it comes to Jave 8. But sorting based on Objects inside a list of Objects needs attention

// Sort method under Collection takes the same comparator
list.sort(Comparator.comparing(String::toString, (String a, String b) -> Integer.parseInt(a.substring(2)) - Integer.parseInt(b.substring(2))));
list.sort(Comparator.comparing(String::toString,comparator.reversed()));

// Single Line Implementation using Collections Arrays Utility Class
Collections.sort(list, ((String a, String b) -> Integer.parseInt(a.substring(2)) - Integer.parseInt(b.substring(2))));

Comparator<String>  comparator = (String a, String b) -> Integer.parseInt(a.substring(2)) - Integer.parseInt(b.substring(2));
Collections.sort(list, comparator);
list.sort(comparator);

View Class Structure


View Sample Data

If we have a list of EventComments and the sort is based on the following criterion :-

  • if we wish to compare based on one arbitrary field index inside SomeClass object
eventCommentsList.sort((object1, object2) -> {
    return object1.getSomeClass().getIndex().compareTo(object2.getSomeClass().getIndex());
});
  • if the requirement is to compare (reversed sort) based on a field timeDtDisplay in the value of first element of the list Object List<SomeStats> someStats.

Notice the placement of the object2 in comparison to object1 for reverse sorting.

eventCommentsList.sort((object1, object2) -> {
    return object2.getSomeStats().get(0).getTimeDtDisplay().compareTo(object1.getSomeStats().get(0).getTimeDtDisplay());
});
  • if the requirement is to compare based on some field index of SomeClass Object and if the index is equal, then use the field timeDtDisplay from the first element of the List of SomeStats
eventCommentsList.sort(
    (EventComments o1, EventComments o2) -> {
       if(o1.getSomeClass().getIndex() > o2.getSomeClass().getIndex())
           return -1;
       else if(o1.getSomeClass().getIndex() < o2.getSomeClass().getIndex())
           return 1;
       else {
           return (o2.getSomeStats().get(0).getTimeDtDisplay().compareTo(o1.getSomeStats().get(0).getTimeDtDisplay()));
       }
    });

Please notice that the code has been reduced from this longer version, where the Comparator interface is being implemented the older way.

eventCommentsList.sort(new Comparator<EventComments>() {
        @Override
        public int compare(EventComments o1, EventComments o2) {
           if(o1.getSomeClass().getIndex() > o2.getSomeClass().getIndex())
               return -1;
           else if(o1.getSomeClass().getIndex() < o2.getSomeClass().getIndex())
               return 1;
           else {
               return (o2.getSomeStats().get(0).getTimeDtDisplay().compareTo(o1.getSomeStats().get(0).getTimeDtDisplay()));
           }
        }
    });
Sorting a Primitive list
Sorting a list of certain Type
Sorting a set

Old & Filthy way of sorting a list

Tags:

Categories:

Updated: