Collections Sorting in Java

We can sort the collection or arrays in Java using callback method like sort from collections utility class and arrays utility class.

Sorting arrays and collections containing primitive types of data :

Sorting collections containing Primitive does not require extra effort apart from using existing functions .
For arrays sorting we use the method Arrays.sort();
For collection sorting we use the method Collections.sort();

Let’s start with primitive sorting

  1. package com.kb.collections_sorting;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.Collections;
  6. import java.util.List;
  7.  
  8. public class PrimitiveSorting {
  9.    
  10. public static void main(String[] args) {
  11.    
  12.     int[] arrayOfIntegers = {3,1,0,7};
  13.    
  14.     Arrays.sort(arrayOfIntegers);
  15.    
  16.     System.out.println("sorted array of integers are ");
  17.     System.out.println(Arrays.toString(arrayOfIntegers));
  18.    
  19.     String[] arrayOfStrings = {"hai","how","are","you"};
  20.     System.out.println("sorted array of strings are ");
  21.     Arrays.sort(arrayOfStrings);
  22.     System.out.println(Arrays.toString(arrayOfStrings));
  23.    
  24.     List stringList = new ArrayList();
  25.     stringList.add("java");
  26.     stringList.add("unix");
  27.     stringList.add("shell script");
  28.     stringList.add("j2ee");
  29.  
  30.     Collections.sort(stringList);
  31.     System.out.println("sorted list of integers are ");
  32.     for (Object element : stringList) {
  33.         System.out.println(element);
  34.     }
  35. }
  36. }
package com.kb.collections_sorting;

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

public class PrimitiveSorting {
	
public static void main(String[] args) {
	
	int[] arrayOfIntegers = {3,1,0,7};
	
	Arrays.sort(arrayOfIntegers);
	
	System.out.println("sorted array of integers are ");
	System.out.println(Arrays.toString(arrayOfIntegers));
	
	String[] arrayOfStrings = {"hai","how","are","you"};
	System.out.println("sorted array of strings are ");
	Arrays.sort(arrayOfStrings);
	System.out.println(Arrays.toString(arrayOfStrings));
	
	List stringList = new ArrayList();
	stringList.add("java");
	stringList.add("unix");
	stringList.add("shell script");
	stringList.add("j2ee");

	Collections.sort(stringList);
	System.out.println("sorted list of integers are ");
	for (Object element : stringList) {
		System.out.println(element);
	}
}
}

Output

anyway array is a collection of similar data means data of same datatype.
Now what if the list contains elements of different types in it as it is not generic list.
Lets see the below program

  1. package com.kb.collections_sorting;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.List;
  6.  
  7. public class PrimitiveSortingWithMultipleTypesOfData {
  8.  
  9.     public static void main(String[] args) {
  10.         List stringList = new ArrayList();
  11.         stringList.add(2);
  12.         stringList.add("unix");
  13.         stringList.add(1);
  14.         stringList.add(true);
  15.  
  16.         Collections.sort(stringList);
  17.         System.out.println("sorted list of integers are ");
  18.         for (Object element : stringList) {
  19.             System.out.println(element);
  20.         }
  21.     }
  22.  
  23. }
package com.kb.collections_sorting;

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

public class PrimitiveSortingWithMultipleTypesOfData {

	public static void main(String[] args) {
		List stringList = new ArrayList();
		stringList.add(2);
		stringList.add("unix");
		stringList.add(1);
		stringList.add(true);

		Collections.sort(stringList);
		System.out.println("sorted list of integers are ");
		for (Object element : stringList) {
			System.out.println(element);
		}
	}

}

Output

Note : To sort collections -> all elements of collection should be of same type
So better to use generics with collection to avoid this kind of problem.
Now assume we have a collection of user defined types.

Example we have a list of person in below class.

  1. class Person  {
  2.     String name;
  3.     int age;
  4.  
  5.     public String getName() {
  6.         return name;
  7.     }
  8.  
  9.     public void setName(String name) {
  10.         this.name = name;
  11.     }
  12.  
  13.     public int getAge() {
  14.         return age;
  15.     }
  16.  
  17.     public void setAge(int age) {
  18.         this.age = age;
  19.     }
  20.    
  21.     @Override
  22.     public String toString() {
  23.         return "name is "+name+" age is "+age;
  24.     }
  25.  
  26. }
class Person  {
	String name;
	int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "name is "+name+" age is "+age;
	}

}

Client code

  1. package com.kb.collections_sorting;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.List;
  5. public class CustomTypeSorting {
  6.     public static void main(String[] args) {
  7.         List people = new ArrayList();
  8.         Person p1 = new Person();
  9.         p1.setName("kb");
  10.         p1.setAge(26);
  11.         Person p2 = new Person();
  12.         p2.setName("pachi");
  13.         p2.setAge(27);
  14.         Person p3 = new Person();
  15.         p3.setName("shridhar");
  16.         p3.setAge(25);
  17.         people.add(p1);
  18.         people.add(p2);
  19.         people.add(p3);
  20.         Collections.sort(people);
  21. for (Object person : people) {
  22.     System.out.println(person);
  23. }
  24.     }
  25. }
package com.kb.collections_sorting;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CustomTypeSorting {
	public static void main(String[] args) {
		List people = new ArrayList();
		Person p1 = new Person();
		p1.setName("kb");
		p1.setAge(26);
		Person p2 = new Person();
		p2.setName("pachi");
		p2.setAge(27);
		Person p3 = new Person();
		p3.setName("shridhar");
		p3.setAge(25);
		people.add(p1);
		people.add(p2);
		people.add(p3);
		Collections.sort(people);
for (Object person : people) {
	System.out.println(person);
}
	}
}

See the output

Exception because custom type can not be sorted as it is.
We need to tell the mechanism how it should be sorted. And that mechanism is comparable or comparator

Let’s implement comparable on our person class

  1. class Person implements Comparable<Person>  {
  2.     String name;
  3.     int age;
  4.  
  5.     public String getName() {
  6.         return name;
  7.     }
  8.  
  9.     public void setName(String name) {
  10.         this.name = name;
  11.     }
  12.  
  13.     public int getAge() {
  14.         return age;
  15.     }
  16.  
  17.     public void setAge(int age) {
  18.         this.age = age;
  19.     }
  20.    
  21.     @Override
  22.     public String toString() {
  23.         return "name is "+name+" age is "+age;
  24.     }
  25.  
  26.     @Override
  27.     public int compareTo(Person p) {
  28.         return this.name.compareTo(p.name);
  29.     }
  30.  
  31. }
class Person implements Comparable<Person>  {
	String name;
	int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "name is "+name+" age is "+age;
	}

	@Override
	public int compareTo(Person p) {
		return this.name.compareTo(p.name);
	}

}

Now we have specified the mechanism how our person class has to be sorted ie by using person’s name using comparable interface.
Now run the same client code defined above
Output

Now what if I want to sort on person’s age , also I need sorting on names as well.
So in this scenario we can’t achive by comparable mechanism, we should use comparator mechanism which is as below
We can call sort on comparator as below

Collections.sort(collection,comparator);

So we already have collection of person ie people
Now we need to define comparator class to sort people.
Let’s redefine person class as below

  1. class Person{
  2.     String name;
  3.     int age;
  4.  
  5.     public String getName() {
  6.         return name;
  7.     }
  8.  
  9.     public void setName(String name) {
  10.         this.name = name;
  11.     }
  12.  
  13.     public int getAge() {
  14.         return age;
  15.     }
  16.  
  17.     public void setAge(int age) {
  18.         this.age = age;
  19.     }
  20.    
  21.     @Override
  22.     public String toString() {
  23.         return "name is "+name+" age is "+age;
  24.     }
  25.    
  26.     public static Comparator<Person> nameComparator = new Comparator<Person>() {
  27.         @Override
  28.         public int compare(Person p1, Person p2) {
  29.             return p1.name.compareTo(p2.name);
  30.         }
  31.     };
  32.    
  33.     public static Comparator<Person> ageComparator = new Comparator<Person>() {
  34.         @Override
  35.         public int compare(Person p1, Person p2) {
  36.             return p1.age - p2.age;
  37.         }
  38.     };
  39.  
  40. }
class Person{
	String name;
	int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "name is "+name+" age is "+age;
	}
	
	public static Comparator<Person> nameComparator = new Comparator<Person>() {
		@Override
		public int compare(Person p1, Person p2) {
			return p1.name.compareTo(p2.name);
		}
	};
	
	public static Comparator<Person> ageComparator = new Comparator<Person>() {
		@Override
		public int compare(Person p1, Person p2) {
			return p1.age - p2.age;
		}
	};

}

client code

  1. package com.kb.collections_sorting;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Comparator;
  6. import java.util.List;
  7. import java.util.function.Function;
  8. import java.util.function.ToDoubleFunction;
  9. import java.util.function.ToIntFunction;
  10. import java.util.function.ToLongFunction;
  11.  
  12. public class CustomTypeSorting {
  13.  
  14.     public static void main(String[] args) {
  15.         List people = new ArrayList();
  16.         Person p1 = new Person();
  17.         p1.setName("kb");
  18.         p1.setAge(26);
  19.         Person p2 = new Person();
  20.         p2.setName("pachi");
  21.         p2.setAge(27);
  22.         Person p3 = new Person();
  23.         p3.setName("shridhar");
  24.         p3.setAge(25);
  25.         people.add(p1);
  26.         people.add(p2);
  27.         people.add(p3);
  28.         Collections.sort(people, Person.nameComparator);
  29.         System.out.println("sorting based on name");
  30.         System.out.println("--------------------");
  31. for (Object person : people) {
  32.             System.out.println(person);
  33.         }
  34.         System.out.println("-----------------------");
  35.         System.out.println("sorting based on age");
  36.         System.out.println("-----------------------");
  37.         Collections.sort(people, Person.ageComparator);
  38.         for (Object person : people) {
  39.             System.out.println(person);
  40.         }
  41.     }
  42. }
package com.kb.collections_sorting;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;

public class CustomTypeSorting {

	public static void main(String[] args) {
		List people = new ArrayList();
		Person p1 = new Person();
		p1.setName("kb");
		p1.setAge(26);
		Person p2 = new Person();
		p2.setName("pachi");
		p2.setAge(27);
		Person p3 = new Person();
		p3.setName("shridhar");
		p3.setAge(25);
		people.add(p1);
		people.add(p2);
		people.add(p3);
		Collections.sort(people, Person.nameComparator);
		System.out.println("sorting based on name");
		System.out.println("--------------------");
for (Object person : people) {
			System.out.println(person);
		}
		System.out.println("-----------------------");
		System.out.println("sorting based on age");
		System.out.println("-----------------------");
		Collections.sort(people, Person.ageComparator);
		for (Object person : people) {
			System.out.println(person);
		}
	}
}

Now the output

So comparator should be used whenever we need to sort custom objects based on different atttibutes.

Now what if we want to sort based on age and name both in a single comparator
Requirement:
Sort person based on age first and then on voterId.
Example
If we have 3 person objects as below
P1 -> name kb and age 26 and voter id ab1
P2->name pachi and age 26 and voted id xy2
P3 -> name shridhar and age 26 and voter id cd3
Now if we sort based on age , we will get the output as
name is kb age is 26
name is pachi age is 26
name is shridhar age is 26
but if we observe closely the order of voter id is
kb ab1
shridhar cd3
pachi xy2
so when age is same sorting is happening based on name but I want sorting to happen on voter id when age is same.
Modify the Person pojo to add voter id as below

  1. class Person{
  2.     String name;
  3.     int age;
  4.     String voterId;
  5.  
  6.     public String getName() {
  7.         return name;
  8.     }
  9.  
  10.     public void setName(String name) {
  11.         this.name = name;
  12.     }
  13.  
  14.     public int getAge() {
  15.         return age;
  16.     }
  17.  
  18.     public void setAge(int age) {
  19.         this.age = age;
  20.     }
  21.    
  22. public String getVoterId() {
  23.         return voterId;
  24.     }
  25.  
  26.     public void setVoterId(String voterId) {
  27.         this.voterId = voterId;
  28.     }
  29.  
  30.  
  31.     @Override
  32.     public String toString() {
  33.         return "name is "+name+" age is "+age;
  34.     }
  35.    
  36.    
  37.     public static Comparator<Person> ageVoterIdComparator = new Comparator<Person>() {
  38.         @Override
  39.         public int compare(Person p1, Person p2) {
  40.             int retVal =  p1.age - p2.age;;
  41.             if(retVal == 0){
  42.                
  43.                 return p1.voterId.compareTo(p2.voterId);
  44.             }
  45.             return retVal;
  46.         }
  47.     };
  48.  
  49.    
  50.  
  51. }
class Person{
	String name;
	int age;
	String voterId;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
public String getVoterId() {
		return voterId;
	}

	public void setVoterId(String voterId) {
		this.voterId = voterId;
	}


	@Override
	public String toString() {
		return "name is "+name+" age is "+age;
	}
	
	
	public static Comparator<Person> ageVoterIdComparator = new Comparator<Person>() {
		@Override
		public int compare(Person p1, Person p2) {
			int retVal =  p1.age - p2.age;;
			if(retVal == 0){
				
				return p1.voterId.compareTo(p2.voterId);
			}
			return retVal;
		}
	};

	

}

Implanted comparator is sorting based on age first and if they are same aged people then sorting based on voter id.
Client code

  1. package com.kb.collections_sorting;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.Comparator;
  5. import java.util.List;
  6. import java.util.function.Function;
  7. import java.util.function.ToDoubleFunction;
  8. import java.util.function.ToIntFunction;
  9. import java.util.function.ToLongFunction;
  10.  
  11. public class CustomTypeSorting {
  12.  
  13.     public static void main(String[] args) {
  14.         List people = new ArrayList();
  15.  
  16.         Person p1 = new Person();
  17.         p1.setName("kb");
  18.         p1.setAge(26);
  19.         p1.setVoterId("ab1");
  20.         Person p2 = new Person();
  21.         p2.setName("pachi");
  22.         p2.setAge(26);
  23.         p2.setVoterId("xy2");
  24.         Person p3 = new Person();
  25.         p3.setName("shridhar");
  26.         p3.setAge(26);
  27.         p3.setVoterId("cd3");
  28.         people.add(p1);
  29.         people.add(p2);
  30.         people.add(p3);
  31.  
  32.         System.out.println("-----------------------");
  33.         System.out.println("sorting based on age Voter id");
  34.         System.out.println("-----------------------");
  35.         Collections.sort(people, Person.ageVoterIdComparator);
  36.         for (Object person : people) {
  37.             System.out.println(person);
  38.         }
  39.     }
  40. }
package com.kb.collections_sorting;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;

public class CustomTypeSorting {

	public static void main(String[] args) {
		List people = new ArrayList();

		Person p1 = new Person();
		p1.setName("kb");
		p1.setAge(26);
		p1.setVoterId("ab1");
		Person p2 = new Person();
		p2.setName("pachi");
		p2.setAge(26);
		p2.setVoterId("xy2");
		Person p3 = new Person();
		p3.setName("shridhar");
		p3.setAge(26);
		p3.setVoterId("cd3");
		people.add(p1);
		people.add(p2);
		people.add(p3);

		System.out.println("-----------------------");
		System.out.println("sorting based on age Voter id");
		System.out.println("-----------------------");
		Collections.sort(people, Person.ageVoterIdComparator);
		for (Object person : people) {
			System.out.println(person);
		}
	}
}

Run and see the output

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on