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));
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Java,
- Deep Dive into Java 8 Predicate Interface
- Read and Parse XML file using Java DOM Parser [Java Tutorial]
- Java 8 Predicate Functional Interface isEqual() Method Example
- Convert Multidimensional Array toString In Java
- How to read int value using Scanner Class Java
- Spring Boot AI + LLM + Java Code Example
- Write to a File using Java Stream API
- Implementing Bubble Sort Algorithm using Java Program
- How to Fix XmlBeanDefinitionStoreException in Java SpringBoot ApplicationConfig.xml
- YAML Parser using Java Jackson Library Example
- [Fix] java: integer number too large compilation error
- Convert JSON String to Java GSON Object Example
- Read a file using Java 8 Stream
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Pretty Print JSON String in Java Console Output
- Java JDBC with Join Queries Example
- How to Check For Updates on Windows 11 (Step-by-Step)
- [Fix] java.net.MalformedURLException: unknown protocol
- How to display date and time in GMT Timezone in Java
- Error: LinkageError occurred while loading main class UnsupportedClassVersionError [Eclipse Java]
- How to convert a String to Java 8 Stream of Char?
- RabbitMQ Queue Listener Java Spring Boot Code Example
- 5+ Fibonacci number Series Java Program Examples [ 0 1 1 2 3 ..]
- Handling NullPointerException with Java Predicate
More Posts:
- Emoji Checkbox with Happy (On) and Sad (Off) Face - CSS
- JSON column formatting to preview SharePoint Online file on mouse hover - SharePoint
- Python 3.x - SQLite 3 Database CRUD Operations Examples - Python
- Android Studio emulator/Device logCat logs not displayed - Android-Studio
- ls Command to See Hidden Files - Linux
- Word-wrap Eclipse Console logs - Eclipse
- Add Custom header and footer to Windows Notepad file - NotepadPlusPlus
- The Zsh Shell - Mac Tutorial - MacOS