Posts

Showing posts with the label Sorting List

Sorting the list of objects in Java

This article will explain about sorting the collection of objects. The document will explain how to sort list or set of objects placed in a collection and also what are the pre-requisites to sort any list or set which is having the list of objects . You can sort   List   collections using the java.util.Collections.sort()   method. You can sort these two types of List 's . 1.    List 2.    LinkedList Sorting Objects by their Natural Order To sort a   List   you do this: List list = new ArrayList(); //add elements to the list Collections.sort(list); When sorting a list like this the elements are ordered according to their "natural order" . For objects to have a natural order they must implement the interface   java.lang.Comparable . In other words, the objects must be comparable to determine their order.  Here is how the  Comparable  interface looks: public interface Comparable<T> {   int compareTo(T o); } The   compareTo()   me