Java Program to sort a List in case insensitive order

Java 8Object Oriented ProgrammingProgramming

Let’s say your list is having the following elements −

P, W, g, K, H, t, E

Therefore, case sensitive order means, capital and small letters will be considered irrespective of case. The output would be −

E, g, H, K, P, t, W

The following is our array −

String[] arr = new String[] { "P", "W", "g", "K", "H", "t", "E" };

Convert the above array to a List −

List<String>list = Arrays.asList(arr);

Now sort the above list in case insensitive order −

Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

Example

 Live Demo

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Demo {
   public static void main(String[] argv) throws Exception {
      String[] arr = new String[] { "P", "W", "g", "K", "H", "t", "E" };
      List<String>list = Arrays.asList(arr);
      System.out.println("List = "+list);
      Collections.sort(list);
      System.out.println("Case Sensitive Sort = "+list);
      Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
      System.out.println("Case Insensitive Sort = "+list);
   }
}

Output

List = [P, W, g, K, H, t, E]
Case Sensitive Sort = [E, H, K, P, W, g, t]
Case Insensitive Sort = [E, g, H, K, P, t, W]
raja
Published on 24-Apr-2019 11:35:08
Advertisements