How to Sort a List in Java

We usually have problem to sort the specified list into ascending order, according to the natural ordering of its elements. This article look though how to sort list/arrarylist in java. Assuming you have created a list, added the instantiation of string as the elements of the lists, please note all elements in the list must be able to implement the Comparable interface, and all elements in the list must be mutually comparable.

How Do I Sort It?

Java.util Class Collections consists an exclusive static method sort(), it is introduced in Java standard package. so we can simply call this method Collections.sort() sort to put all elements in order, with this way it is limited to sort only ”basic” objects, e.g. String and the wrapper object of primitive class.

public class SortListDemo{
	public static void main(String[] args) {
		List list = new ArrayList();
		list.add("AA");
		list.add("BB");
		list.add("CC");
		// Sort list
		Collections.sort(list);
		// Print the result after sorting list
		Iterator iterator = list.iterator();
		while (iterator.hasNext()) {
			System.out.print(iterator.next() + " ");
		}
		// Result: AA BB CC
	}
}

More sorting feature such as sorting by Case-insensitive, reverse-order.

                 // sort the list by Case-insensitive
		Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

		// Reverse-order sort
		Collections.sort(list, Collections.reverseOrder());

		// Case-insensitive reverse-order sort
		Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
		Collections.reverse(list);

Making your Java objects sortable: the Comparable interface

In our real program, the expectation is always more complex than we imagine, the element in list is not just a string, this is in case of Sorting the specified list according to the order induced by the specified comparator, we need implement interface comparator and pass it into Collections.sort() method.

public static void sort(List list, Comparator c)

  • Parameters:
    list – the list to be sorted.
    c – the comparator to determine the order of the list. A null value indicates that the elements’ natural ordering should be used.
  • Throws:
    ClassCastException – if the list contains elements that are not mutually comparable using the specified comparator.
    UnsupportedOperationException – if the specified list’s list-iterator does not support the set operation.

Let’s consider an example of a class that represents a student. For simplicity, the student will only have variables number,  first name and last name which both represented by a string. We putted all students into an arraylist disorderly and want it to be sorted by last name.

Implementing Comparable to sort a list

We start by making our class implement the Comparable interface. While implementing this interface, we must overwritten the method compare(Object o1,
Object o2), which is used to Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. and please note your comparator must describe a correct reflexive, symmetric and transitive relation in order for it to work.

package com.oracle;

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

class Student {
	private int number;
	private String lastName;
	private String firstName;

	public Student(int number, String lastName, String firstName) {
		super();
		this.number = number;
		this.lastName = lastName;
		this.firstName = firstName;
	}

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
}

class StudentComparator implements Comparator {

	public int compare(Student paramT1, Student paramT2) {
		if (paramT1 == null) {
			if (paramT2 == null) {
				return 0; // Both students are null
			} else {
				return -1; // paramT1 is NULL, so put paramT1 in the end of
				// the sorted list
			}
		} else {
			if (paramT2 == null) {
				return 1;
			}
		}
		String lastName1 = paramT1.getLastName();
		String lastName2 = paramT2.getLastName();
		return lastName1.compareTo(lastName2);
	}
}

public class SortListExample{
	public static void main(String[] args) {
		List list = new ArrayList();
		list.add(new Student(1, "Tim", "Jonh"));
		list.add(new Student(2, "Gwin", "Shane"));
		list.add(new Student(3, "Steve", "Jonh"));

		// Sort list
		Collections.sort(list, new StudentComparator());
	}
}

Оцените статью
ASJAVA.COM
Добавить комментарий

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

*

code