Sort LinkedList of User-Defined Objects in Java

For sorting a list in Java, you can use sort(List<T> list) method. This method can sort a list in which all elements must implement the Comparable interface.

In the example below, the House class is user-defined. To make it comparable, it implements the Comparable interface. By using the sort(List<T> list) method, it can be sorted in ascending order.

If you want to reverse the sorting order, you can simple use sort(List<T> list, Comparator<? super T> c) . The parameter is Collections.reverseOrder() method. This method returns a Comparator that use the reverse of the natural ordering on a collection of objects that implement the Comparable interface. Since the House class implement Comparable interface, we can use this method to reverse order automatically.

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
 
//sort self-defined object linkedlist in Java
 
class House implements Comparable<House> {
	String type;
	int size;
 
	public House(String t, int s) {
		type = t; 
		size = s;
	}
 
	@Override
	public int compareTo(House o) {
		int comparedSize = o.size;
		if (this.size > comparedSize) {
			return 1;
		} else if (this.size == comparedSize) {
			return 0;
		} else {
			return -1;
		}
	}
 
	public String toString() {
		return type;
	}
}
 
public class SortLinkedList {
	public static void main(String[] args) {
		LinkedList<House> houseList = new LinkedList<House>();
		houseList.add(new House("medium", 200));
		houseList.add(new House("small", 100));
		houseList.add(new House("large", 300));
		System.out.println(houseList);
 
		// sort in ascending order
		Collections.sort(houseList);
		System.out.println(houseList);
 
		// sort in descending order
		Collections.sort(houseList, Collections.reverseOrder());
		System.out.println(houseList);
	}
 
	public static void printList(List l) {
		for (Object o : l) {
			System.out.println(o);
		}
	}
}

Output:

[medium, small, large]
[small, medium, large]
[large, medium, small]

Leave a Comment