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));

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap