Friday 13 January 2012

How to Sort Arraylist in Java Example Tutorial

In 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 willsort 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 alongwith 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 implementsComparator{

        @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}]


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.

No comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More