Sorting arraylist in alphabetical order (case insensitive) in java

Sorting arraylist in alphabetical order (case insensitive) in java

To sort an ArrayList of strings in alphabetical order (case-insensitive) in Java, you can use the Collections.sort() method along with a custom comparator that ignores the case of the strings. Here's how you can do it:

import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class SortArrayListCaseInsensitive { public static void main(String[] args) { // Create an ArrayList of strings List<String> myList = new ArrayList<>(); myList.add("apple"); myList.add("Banana"); myList.add("cherry"); myList.add("Date"); // Sort the ArrayList in alphabetical order (case-insensitive) Collections.sort(myList, String.CASE_INSENSITIVE_ORDER); // Print the sorted ArrayList for (String str : myList) { System.out.println(str); } } } 

In this example:

  1. We create an ArrayList called myList and add some strings to it.
  2. We use the Collections.sort() method to sort the myList in alphabetical order. We pass String.CASE_INSENSITIVE_ORDER as a comparator to perform a case-insensitive sorting.

After sorting, the myList will contain the strings in alphabetical order, with case-insensitivity taken into account.

The output will be:

apple Banana cherry Date 

As you can see, the strings are sorted alphabetically regardless of their case.


More Tags

window.onunload value-type phpmailer react-server filechooser collision git-rm color-detection invalid-object-name dos

More Java Questions

More Electronics Circuits Calculators

More Fitness-Health Calculators

More Biology Calculators

More Physical chemistry Calculators