
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);
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);
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));
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!