Home > Collections > How to sort a list of objects

How to sort a list of objects

Ever wondered how to sort a list full of custom objects? The answer is to use a Comparator (or Comparable).

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

public class Sorter
{
    private static Comparator<Product> COMPARATOR = new Comparator<Product>()
    {
	// This is where the sorting happens.
        public int compare(Product o1, Product o2)
        {
            return o1.getPrice() - o2.getPrice();
        }
    };
    
    public static void main(String[] args)
    {
	Product product1 = new Product(1, 20);
	Product product2 = new Product(1, 1);
	Product product3 = new Product(3, 30);
	Product product4 = new Product(6, 6);
	Product product5 = new Product(4, 45);
	Product product6 = new Product(6, 3);
	
	List<Product> products = new ArrayList<Product>(6);
	products.add(product1);
	products.add(product2);
	products.add(product3);
	products.add(product4);
	products.add(product5);
	products.add(product6);
	
	for (Product product : products)
	    System.out.println("Before sorting on price: " + product.getPrice());
	
	Collections.sort(products, COMPARATOR);
	
	for (Product product : products)
	    System.out.println("After sorting on price: " + product.getPrice());
    }
}

class Product
{
    int code, price;

    public Product(int code, int price)
    {
	this.code = code;
	this.price = price;
    }

    public int getCode()
    {
        return code;
    }

    public int getPrice()
    {
        return price;
    }
}

What if you want to sort based on two (or more) properties in the class. Lets say that we want to sort first on code and then on price (a product might have many prices, depending on who is buying it). Then we need to change the compare method to the following

// This is where the sorting happens.
	public int compare(Product o1, Product o2)
	{
	    int codeDifference = o1.getCode() - o2.getCode();
	    // If the code is the same then sort on the price.
	    if (codeDifference == 0)
		return o1.getPrice() - o2.getPrice();
	    else
		return codeDifference;
	}

It will first sort on the product code and, if it is the same between two products, it will further sort on the price of each product.

Advertisements
Categories: Collections Tags: , ,
  1. vTechMonks
    1 November 2010 at 7:50 pm

    Nice Topic! And clear Example.

  2. don
    8 November 2011 at 7:36 am

    Good sample..! Thanks….

  3. jagadeesh
    30 November 2011 at 5:22 pm

    excellent example

  4. Nguyen
    27 March 2012 at 11:21 am

    Thank you. Very easy to understand..

  5. nakurato
    27 April 2012 at 2:06 am

    Very helpful, solve our use case in 30 mins… Thanks.

  6. 8 January 2013 at 6:51 pm

    thanks, very useful, clear and very concise.

  7. Jennifer
    16 January 2013 at 1:54 pm

    how about “String” type comparision?

    • 16 January 2013 at 2:39 pm

      You simply use the “compareTo()” method of the string and return the result.

      return stringa.compareTo(stringb);

  8. 15 May 2013 at 2:51 am
  9. pepe
    22 May 2013 at 8:52 pm

    Very good example. Thanks.

  10. anon
    28 January 2014 at 7:32 pm

    Thank you, very good example

  1. 19 January 2012 at 10:34 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: