Sorting Java Arraylist


The elements of List are shown in order they were added. There are times, when we need to sort the List in certain order. It can be done using Collections class. In this example, we can see use of Collections.sort() to sort the ArrayList. It sort specified list into ascending order, according to the natural ordering of its elements. The elements implements Comparable interface and performs pairwise comparison of the elements and returns 0 if it is equal, -1 if it smaller and 1 if it is larger than compared elements.

public void sort(){
		List<String> unsortedList=new ArrayList<String>();
		System.out.println("Unsorted ArrayList:");
		unsortedList.add("Mercury");
		unsortedList.add("Earth");
		unsortedList.add("Venus");
		unsortedList.add("Mars");
		for(String s : unsortedList){
			System.out.println(s);
		}
		System.out.println("");

		System.out.println("Sorted ArrayList:");
		Collections.sort(unsortedList);
		for(String s : unsortedList){
			System.out.println(s);
		}
	}


Output from above sample:

Unsorted ArrayList:
Mercury
Earth
Venus
Mars

Sorted ArrayList:
Earth
Mars
Mercury
Venus


We can also define implemention based on Comparator interface to sort ArrayList as required. In this example, we create a Java class ‘Task’ with attributes ‘title’ & ‘priority’ of type String and int respectively.

public class Task {
	private String title;
	private int priority;

	public Task(String title, int priority) {
		this.title = title;
		this.priority = priority;
	}

	// getter & setter 
}


We also define a Comparable, which compares every object by attribute priority of type int.

public class ListComparable implements Comparator<Task>{

	@Override
	public int compare(Task t1, Task t2) {
		return (t1.getPriority()<t2.getPriority() ? -1 : (t1.getPriority()==t2.getPriority() ? 0 : 1));
	}
}

Add couple of object of type Task to ArrayList and print it out in console. Without sorting, elements are displayed as they were added to ArrayList. By using own comparable, we can sort the provided the ArrayList in ascending according to their priority value.

public void sort() {
		List<Task> tasks = new ArrayList<Task>();

		tasks.add(new Task("Take out trash", 2));
		tasks.add(new Task("Go to work", 3));
		tasks.add(new Task("Clean room", 1));
		
		System.out.println("Unsorted");
		for (Task t : tasks) {
			System.out.println(t.getTitle()+" "+t.getPriority());
		}
		System.out.println("Sorted");
		Collections.sort(tasks, new ListComparable());
		for (Task t : tasks) {
			System.out.println(t.getTitle()+" "+t.getPriority());
		}
	}


Output from above sample:

Unsorted
Take out trash 2
Go to work 3
Clean room 1

Sorted
Clean room 1
Take out trash 2
Go to work 3

Leave a comment

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.