How to Sort a LinkedList in Java


Sort An ArrayList in Java Example

Let's say we have an ArrayList of countries, as in ArrayList the insertion order is preserved by default the output is in the inserted order of the elements we added using the add method.

LinkedList<String> countriesList = new LinkedList<>();
countriesList.add("China");
countriesList.add("USA");
countriesList.add("Germany");
countriesList.add("France");
countriesList.add("India");
countriesList.add("Sweden");
countriesList.add("Australia");

System.out.println(countriesList);

[China, USA, Germany, France, India, Sweden, Australia]

Now let's take a look at various ways in which we can sort this ArrayList object.


Option 1: Using Collections.sort() method

    Collections.sort(countriesList);

    [Australia, China, France, Germany, India, Sweden, USA]


Option 2: Using LinkedList.sort() method:

    countriesList.sort(null);

Option 3: Using Comparator

    Comparator<String> comparator = (o1, o2) -> o1.compareTo(o2);
    countriesList.sort(comparator);

Option 4: Using Java 8 Stream API

    list = countriesList.stream().sorted().collect(Collectors.toCollection(LinkedList::new));
-




Have Questions? Post them here!