Sorting Lists

  • For the manipulation of data in different collection types, the Java API provides a Collections class , which is included in the java.utilĀ  package.
  • One of the most popular Collections class method is sort() . which sorts the elements of your Collection type.
  • The method is the Collections class are static , you doesn’t need a Collections objects to call them.
  • Example-
    public class Myclass{
          public static void main(String args[]){
               ArrayList<String> animals = new ArrayList<String>();
               animals.add("tiger");
               animals.add("cat");
               animals.add("snake");
               animals.add("dog");
               Collection.sort(animals);
               System.out.println(animals);  
         }
    }
    output-
    [cat , dog , snake , tiger]
  • Example-
    public class Myclass{
         public static void main(String args[]){
             ArrayList<Integer> num = new ArrayList<Integer>();
             num.add(3);
             num.add(36);
             num.add(12);
             num.add(1);
             Collection.sort(num);
             System.out.println(num); 
      }
    }
    Output-
    [1 , 3 , 12 ,36]
  • Other Useful methods in the Collections:
  • max(Collection c) – Returns the max elements in c as determined by natural ordering.
  • min(Collection c) – Returns the min elements in c as determined by natural ordering.
  • reverse(List list) – Reverse the element in list.
  • shuffle(List list) – (randomize) the element in list.