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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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);
    }
}
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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);
        }
    }
 
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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;
    }
 
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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);
}
    }
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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);
    }
 
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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;
        }
    };
 
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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);
        }
    }
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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;
        }
    };
 
    
 
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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);
        }
    }
}
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

Karibasappa G C (KB)
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