Tutorials Java How to sort an ArrayList in java

How to sort an ArrayList in java

ArrayList are also called as dynamic arrays that can grow as needed. In Java ArrayList class extends AbstractList and implements List interface. In Java ArrayList’s are created with an initial size. The size of the collection is changes dynamically as the items are exceeded the size or deleted. This example will explain sorting of ArrayList using Comparator, Comparable and Collectiolns.sort() method.

[box style=”1″]Note: Typically standard Array in java is fixed sized in nature. Once created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.[/box]

At times, you may need to sort the ArrayList to make it alphabetically order. In this below example, it shows the use of Collections.sort and comparator to sort an ArrayList.

1. Sorting using Collections.sort method:

public class SortArrayList {

	public static void main(String[] args) {
		ArrayList unsortList = new ArrayList();
		unsortList.add("1011");
		unsortList.add("5460");
		unsortList.add("1000");
		unsortList.add("Abdul");
		unsortList.add("1012");
		unsortList.add("Adam");

		System.out.println("********** Value before sorting **************");
		for (String str : unsortList) {
			System.out.println(str);
		}

		Collections.sort(unsortList);

		System.out.println("********** Value after sorting **************");
		for (String str : unsortList) {
			System.out.println(str);
		}

	}
}

Here in this above example the sorting happens according to ASCII.

Output:

sorting-array-list-using-collections.sort

 2. Sorting objects in an ArrayList using Comparable interface

In my example I want to sort the employees list as per their salary in descending order. My Employee class implements Comparable interface and overridden compareTo method. In Compare to method add your logic, weather to sort ascending or descending order.

public class Employee implements Comparable {
	private String name;
	private String id;
	private double salary;

	public Employee(String id, String name, double salary) {
		this.id = id;
		this.name = name;
		this.salary = salary;
	}

	public String getName() {
		return name;
	}

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

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	@Override
	public int compareTo(Employee employee) {
		double compareSalary = ((Employee) employee).getSalary();

		// ascending order
		// return (int) (this.salary - compareSalary);

		// descending order
		return (int) (compareSalary - this.salary);
	}

	@Override
	public String toString() {
		return "[ id=" + id + ", name=" + name + ", salary=" + salary + "]";
	}

}

3. Sorting Objects in an ArrayList using Comparator

Check out the below code snippet, I am sorting Employees list using Anonymous Comparator

//Sorting using Anonymous inner class type
		Collections.sort(emplyoees, new Comparator() {
			@Override
			public int compare(Employee e1, Employee e2) {
				String id1 = ((Employee) e1).getId();
				String id2 = ((Employee) e2).getId();

				// ascending order
				 return id1.compareTo(id2);

				// descending order
				//return id2.compareTo(id1);
			}
		});
Complete Code
public class SortArrayListObjects {

	public static void main(String[] args) {

		ArrayList employees = new ArrayList();
		employees.add(new Employee("1001", "Adam", 5000));
		employees.add(new Employee("1006", "Rajan", 8400));
		employees.add(new Employee("1040", "Keay", 2500));
		employees.add(new Employee("1056", "Ashok", 12000));	

		System.out.println("**** Value before sorting ***");
		for(Employee employee: employees){
			System.out.println(employee);
		}

		Collections.sort(employees);

		System.out.println("**** After sorting salary descending ***");
		for(Employee employee: employees){
			System.out.println(employee);
		}

		//Sorting using Anonymous inner class type
		Collections.sort(employees, new Comparator() {
			@Override
			public int compare(Employee e1, Employee e2) {
				String id1 = ((Employee) e1).getId();
				String id2 = ((Employee) e2).getId();

				// ascending order
				 return id1.compareTo(id2);

				// descending order
				//return id2.compareTo(id1);
			}
		});

		System.out.println("**** After sorting id ascending ***");
		for(Employee employee: employees){
			System.out.println(employee);
		}

	}
}
Outputsorting-array-list-using-Comparator

 

Total
0
Shares
guest
8 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Hesham Mohmed
Hesham Mohmed
9 years ago

hello ..
thanx alot but where the arraylist class

Hesham Mohmed
Hesham Mohmed
9 years ago

can you write the full code with all class plz ?

javatechig
javatechig
9 years ago
Reply to  Hesham Mohmed

Complete code is provided in the tutorial. You may like to revisit.

Mousami
Mousami
8 years ago

Hi Sir, thank you for your tech blog.. your blog helps me in learning android…

Nilanchala Panigrahy
Nilanchala Panigrahy
7 years ago

Sorry. Don’t have a sample ready for you.

Leslie
Leslie
7 years ago

FYI emplyoee is spelled employee

Nilanchala Panigrahy
Nilanchala Panigrahy
7 years ago
Reply to  Leslie

Thanks Leslie for pointing it out. fixed now..

infoj
infoj
7 years ago

One thing to note here is that sorting will be done in natural ordering and it happens because String class implements Comparable interface and provides implementation for the method compareTo(String anotherString) .. If sorting is to be done in reverse order then we have to use custom comparator or there is also reverseOrder method provided by Collections class.

See some of the ways to sort arraylist here –

http://netjs.blogspot.com/2015/08/how-to-sort-arraylist-of-custom-objects-java.html

and here
http://netjs.blogspot.com/2015/08/how-to-sort-arraylist-in-java.html

Previous Post
Java Tutorials

How To Loop ArrayList In Java

Next Post
Android Tutorials

Loading Image Asynchronously in Android ListView

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
8
0
Would love your thoughts, please comment.x
()
x