In this post, we will look at how we can sort a LinkedList in Java using some inbuilt functions. We will be looking at the below points.
- How to sort a LinkedList in ascending order?
- Second, how to sort a LinkedList in descending order?
- And lastly, we will see how we can sort a Linked List of custom-made objects?
Let’s have a look at all of them one by one.
How to sort a LinkedList in ascending order?
We will be using the Collections.sort() method of the Collections class in java.util package to sort the linked list.
What does this method do? It will accept a list as an argument and sort the list in ascending order ( according to the natural ordering of the element ). It is a static method, so we can directly call this method using its class name.
Note: To use this method, the elements of the LinkedList must implement a Comparable interface, and all of the elements of the LinkedList should also be mutually comparable.
Code Example
import java.util.Collections;
import java.util.LinkedList;
public class Codekru {
public static void main(String[] args) {
LinkedList<Integer> li = new LinkedList<Integer>();
li.add(62);
li.add(53);
li.add(42);
li.add(23);
li.add(453);
System.out.println("LinkedList before sorting: " + li.toString());
Collections.sort(li); // sorting the elements of the linked list
System.out.println("LinkedList after sorting in ascending order: " + li.toString());
}
}
Output –
LinkedList before sorting: [62, 53, 42, 23, 453]
LinkedList after sorting: [23, 42, 53, 62, 453]
Sorting a linked list in descending order
Sorting a linked list in descending order is pretty easy as we only have to reverse the linked list sorted in ascending order ( which we already did above).
We will be using the Collections.reverse() function, a static function to reverse the list passed in its arguments. So, sorting a linked list in descending order is only a two-step process –
- Sort the linked list in ascending order.
- And then reverse the linked list.
import java.util.Collections;
import java.util.LinkedList;
public class Codekru {
public static void main(String[] args) {
LinkedList<Integer> li = new LinkedList<Integer>();
li.add(62);
li.add(53);
li.add(42);
li.add(23);
li.add(453);
System.out.println("LinkedList before sorting: " + li.toString());
Collections.sort(li); // sorting the elements of the linked list
Collections.reverse(li); // reversing the linked list
System.out.println("LinkedList after sorting in descending order: " + li.toString());
}
}
Output –
LinkedList before sorting: [62, 53, 42, 23, 453]
LinkedList after sorting in descending order: [453, 62, 53, 42, 23]
Sorting a LinkedList of custom-made objects
Let’s make a class named Person having two variables ( age and height ), and we will try to sort a list of Person objects based on their age in ascending order. We have not made any getters and setters methods to make the code look shorter. 😛
Person.java
class Person {
int age;
int height;
public Person(int age, int height) {
this.age = age;
this.height = height;
}
// using toString() method to print only the person's age
public String toString() {
return "Person's age: " + age;
}
}
Now, as we want to sort based on age, we will have to implement the Comparator interface and its compare method.
class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
return o1.age - o2.age;
}
}
Now, what would the above piece of code do? It would help us compare two person objects based on their age and sort them in ascending order. If you want to sort them in descending order, you must reverse the result returned by the compare function.
Collections.sort() method has one more overloaded static method that accepts two arguments – one is the list itself, and another is the implemented class of the comparator, which is PersonComparator in our case. So, we will have to pass the LinkedList along with the PersonComparator in the Collection.sort() function to sort the Person’s object list based on their age.
Complete example
class Person {
int age;
int height;
public Person(int age, int height) {
this.age = age;
this.height = height;
}
// using toString() method to print only the person's age
public String toString() {
return "Person's age: " + age;
}
}
class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
return o1.age - o2.age;
}
}
public class Codekru {
public static void main(String[] args) {
LinkedList<Person> li = new LinkedList<Person>();
li.add(new Person(11,124));
li.add(new Person(9,134));
li.add(new Person(8,104));
li.add(new Person(43,184));
System.out.println("LinkedList before sorting: " + li.toString());
PersonComparator pc = new PersonComparator();
Collections.sort(li,pc); // sorting the elements of the linked list
System.out.println("LinkedList after sorting in descending order: " + li.toString());
}
}
Output –
LinkedList before sorting: [Person's age: 11, Person's age: 9, Person's age: 8, Person's age: 43]
LinkedList after sorting in descending order: [Person's age: 8, Person's age: 9, Person's age: 11, Person's age: 43]
Here, we have sorted the LinkedList of Person objects in the ascending order of their age.
What if we try to use the Collection.sort() method on a list containing different types of objects?
Here, we will take a linked list with elements of type Integer and String and then try to sort it using the Collection.sort() function.
public class Codekru {
public static void main(String[] args) {
LinkedList<Object> li = new LinkedList<Object>();
li.add(3);
li.add(45);
li.add("hello");
li.add("codekru");
System.out.println("LinkedList before sorting: " + li.toString());
Collections.sort(li); // sorting the elements of the linked list
System.out.println("LinkedList after sorting in descending order: " + li.toString());
}
}
Output –
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method sort(List<T>) in the type Collections is not applicable for the arguments (LinkedList<Object>)
We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.