Skip to content

Java LinkedList Sort Example

This example shows how to sort the elements of the LinkedList in Java. The example also shows how to sort the LinkedList using the Comparator and Comparable interfaces.

How to sort LinkedList in Java?

We can use the sort method of the Collections class to sort the elements of the LinkedList.

The above method takes a List as an argument. Since the LinkedList class implements the List interface, we can use this method to sort the LinkedList object.

Output

As you can see from the output, the linked list elements are sorted in ascending order by the sort method. The sort method orders the elements in their natural order which is ascending order for the type Integer.

Note: The LinkedList elements must implement the Comparable interface for this method to work. The below given example shows how to do that in a custom class.

Output

As you can see from the output, the compareTo method defines the natural ordering of the Student objects.

How to sort the LinkedList containing custom class objects using a Comparator?

We have seen how to sort the linked list elements using the Comparable interface. In the following example, I will show you how to sort the LinkedList using the Comparator interface. I am going to use the same Student class for this example.

Output

This example is a part of the LinkedList in Java tutorial.

Please let me know your views in the comments section below.

References:
Java 8 LinkedList
Java 8 Collections class

About the author

Leave a Reply

Your email address will not be published.