Monday, January 9, 2012

How to Sort Java ArrayList in Descending Order - Example Tutorial

Sorting ArrayList in Java is a common task for Java developer and we have touched it while discussing
10 Example of  ArrayList in Java and again when we discussed comparator and comparable in Java. In order to sort an arraylist we need to use Collections utility class which contains overloaded sort() method for sorting different collections and  supports different comparator in Java. In this article we will see How to sort ArrayList with natural order of element and than sorting ArrayList in Java with comparator.

Sort ArrayList in Ascending and Descending order

Sorting ArrayList in Java with natural Order

how to sort arraylist in java example codeIn Order to Sort Java ArrayList on natural order of elements, object stored in ArrayList must implement Comparable interface in Java and should override compareTo() method as per there natural order. In our example of natural order sorting in ArrayList we have implemented compareTo of smartphone and sorted them based on brands. So an Apple smartphone comes before Nokia smartphone. Once your object is OK just store them in Java arraylist and pass that list to Collections.sort() method, this will sort the list in natural order of objects. see bottom of this java tutorial for complete code example of Sorting Java ArrayList in Natural Order.

Sorting Java ArrayList with custom Order

To Sort a Java arraylist on Custom order we need to supply an external Comparator along-with Arraylist to Collections.sort(List, Comparator) method. Compare() method will define how sorting of objects will take place in ArrayList.In our example of custom order sorting of Java Arraylist we have created a PriceComparator which sorts objects based on there price. So you can get cheapest or expensive smartphone stored in ArrayList. See below for full code example of ArrayList Sorting in custom order in Java:

Code Example of Sorting ArrayList in Java

Here is complete code example of sorting an arraylist in java on both natural and custom order by using Custom comparator.

package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ArrayListSortingExample {

   private static class SmartPhone implements Comparable {
        private String brand;
        private String model;
        private int price;

        public SmartPhone(String brand, String model, int price){
            this.brand = brand;
            this.model = model;
            this.price = price;
        }
      
        @Override
        public int compareTo(SmartPhone sp) {
            return this.brand.compareTo(sp.brand);
        }

        @Override
        public String toString() {
            return "SmartPhone{" + "brand=" + brand + ", model=" + model + ", price=" + price + '}';
        }
      
    }
  
    private static class PriceComparator implements Comparator{

        @Override
        public int compare(SmartPhone sp1, SmartPhone sp2) {
            return (sp1.price < sp2.price ) ? -1: (sp1.price > sp2.price) ? 1:0 ;
        }
      
    }

    public static void main(String... args) {
      
        //creating objects for arraylist sorting example
        SmartPhone apple = new SmartPhone("Apple", "IPhone4S",1000);
        SmartPhone nokia = new SmartPhone("Nokia", "Lumia 800",600);
        SmartPhone samsung = new SmartPhone("Samsung", "Galaxy Ace",800);
        SmartPhone lg = new SmartPhone("LG", "Optimus",500);
      
        //creating Arraylist for sorting example
        ArrayList smartPhones = new ArrayList();
      
        //storing objects into ArrayList for sorting
        smartPhones.add(apple);
        smartPhones.add(nokia);
        smartPhones.add(samsung);
        smartPhones.add(lg);
      
        //Sorting Arraylist in Java on natural order of object
        Collections.sort(smartPhones);
      
        //print sorted arraylist on natural order
        System.out.println(smartPhones);
      
        //Sorting Arraylist in Java on custom order defined by Comparator
        Collections.sort(smartPhones,new PriceComparator());
      
        //print sorted arraylist on custom order
        System.out.println(smartPhones);
    
    }
}

Output:
[SmartPhone{brand=Apple, model=IPhone4S, price=1000}, SmartPhone{brand=LG, model=Optimus, price=500}, SmartPhone{brand=Nokia, model=Lumia 800, price=600}, SmartPhone{brand=Samsung, model=Galaxy Ace, price=800}]

[SmartPhone{brand=LG, model=Optimus, price=500}, SmartPhone{brand=Nokia, model=Lumia 800, price=600}, SmartPhone{brand=Samsung, model=Galaxy Ace, price=800}, SmartPhone{brand=Apple, model=IPhone4S, price=1000}]


How to sort ArrayList in Descending Order in Java

ArrayList can also be sorted in descending or reverse order by using Collections.reverseOrder() and Collection.reverseOrder(Comparator cmp). Former method will sort in reverse order of natural ordering while later method will sort in the reverse order of specified comparator as shown in following example of sorting arraylist into reverse order :

//sorting ArrayList in descending or reverse order in Java
List unsortedList = Arrays.asList("abc", "bcd", "ade", "cde");
Collections.sort(unsortedList, Collections.reverseOrder());

System.out.println("Arraylist in descending order: " + unsortedList);


Output:
ArrayList before sorting in reverse order: [abc, bcd, ade, cde]
Arraylist in descending order: [cde, bcd, ade, abc]

How to sort ArrayList of String  in Case insensitive Order

ArrayList  of String can also be sorted with case insensitive comparison. String class defines a convenient case insensitive comparator which can be accessed directly like String.CASE_INSENSITIVE_ORDER . if you pass this comparator to ArrayList.sort() which contains String then those will be sorted accordingly. Here is an example of sorting arraylist in case insensitive order:

//sorting ArrayList on case insensitive order of String
unsortedList = Arrays.asList("abc", "bcd", "ABC", "BCD");
System.out.println("ArrayList before case insensitive sort: " + unsortedList);
             
Collections.sort(unsortedList, String.CASE_INSENSITIVE_ORDER);
System.out.println("ArrayList after case insensitive sort: " + unsortedList);

Output:
ArrayList before case insensitive sort: [abc, bcd, ABC, BCD]
ArrayList after case insensitive sort: [abc, ABC, bcd, BCD]


That’s all on Sorting ArrayList in Java based on natural order of Object and any custom order by using Custom Comparator. Let me know if you face any issue while running Sorting ArrayList Example code in Java and I wold be glad to help you.

Thanks

Java Tutorials you may Like

14 comments :

Anonymous said...

Should have mention that Object should be implemented Comparable interface in order to them to be sorted in Arraylist in natural order. first natural order is applied and than ascending or descending which determine direction.

Radhika said...

I really like different kind of comparator Java provides like reverse comparator which can be used to sort List in descending order, Case Insensitive Comparator which can be used to Sort array in case insensitive order. Can you please give example of sorting arraylist in two different columns e.g. first name and than surname ?

Anonymous said...

good example on how to sort arraylist in java but I guess this method can also be used to sort other List implementation like Vector and LinkedList, isn't it ?

Anonymous said...

how to sort arraylist in java - Use Collections.sort
how to sort arraylist of objects in java - Use collections.sort with compareTo
how to sort arraylist in java using comparator - pass Comparator to sort()
how to sort arraylist in descending order in java - use reverseComparator() and pass that to sort

Sorting said...

wow I didn't know that there is a built in Comparator exists to compare Strings in CASE INSENSITIVE order. that is kind of nice little find for me. on related note what is difference between an ordered collection or Sorted collection, isn't it both the same ? is ArrayList a sorted collection or ordered collection ?

Anonymous said...

Is the price comparator working? I tried the code.but it's not behaving as expected.The method compare(SmartPhone sp1, SmartPhone sp2) is overloaded instead of overrididng isn't it?

Javin @ CyclicBarrier Example Java said...

@Anonymous, you are write compare() expect Object so its overloaded, should have used @Override to prevent that, that is very hard to find bug if you are not using @Override annotation. thanks for pointing it. I will correct it.

Vijendra Singh said...

what is the use of class which is create inside a interface...

Anonymous said...

Hi,

i am not satisfied with the program.my query is as :
we need to sort data dynamically according to date wise or int type or some time ascending or descending order.. please assist here...


Thx,
Saurabh

Anonymous said...

Above code is not compilling in Java7.
Did anyone noticed?

Javin @ puzzle asked in programming interviews said...

@Anonymous, What is the error you are getting? Can you post compilation error here?

Anonymous said...

thank you very much for your kind information...

Kevin Jaques said...

My compiler complained that the interfaces were not implemented. When I let it suggest corrections, it added compare(Object) and compareTo(Object,Object) methods. Further research revealed that both interfaces should have been 'parametized'. Basically, that means just adding to the Class definitions so that the first reads "private static class SmartPhone implements Comparable" and the second reads "private static class PriceComparator implements Comparator"

Apparently the interfaces are written for generic object types, so you have to specify which types you want to handle.

Anonymous said...

Should be as follows:

public class ArrayListSortingExample {

private static class SmartPhone implements Comparable {

private String brand;
private String model;
private int price;

public SmartPhone(String brand, String model, int price) {
this.brand = brand;
this.model = model;
this.price = price;
}

@Override
public int compareTo(Object sp) {
return this.brand.compareTo(((SmartPhone) sp).brand);
}

@Override
public String toString() {
return "SmartPhone{" + "brand=" + brand + ", model=" + model + ", price=" + price + '}';
}

}

private static class PriceComparator implements Comparator {

@Override
public int compare(Object sp1, Object sp2) {
return (
((SmartPhone) sp1).price < ((SmartPhone) sp2).price) ? -1
: (((SmartPhone) sp1).price > ((SmartPhone) sp2).price) ? 1 : 0;
}

}

and please fix it - preview to be available before author approval...

Post a Comment