
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort a List in Case-Sensitive Order in Java
In this article, we will learn to sort a List in case-sensitive order in Java. Sorting in case-sensitive order places uppercase letters before lowercase letters (e.g., 'A' before 'a'), meaning that uppercase letters are prioritized in sorting. This program uses Java's built-in Collections.sort method to arrange elements in this specific order.
Problem Statement
Given a list of mixed uppercase and lowercase letters, write a Java program that sorts the list in a case-sensitive order.
Input
{ "P", "W", "g", "K", "H", "t", "E" }
Output
List = [P, W, g, K, H, t, E]
Case Sensitive Sort = [E, H, K, P, W, g, t]
Steps to sort a list in case-sensitive order
Following are the steps to sort a list in case-sensitive order ?
- First, we will import the Arrays, Collections, and List classes from java.util package
- Create an array of strings with both uppercase and lowercase letters.
- After that we will convert the array to a list using Arrays.asList, allowing us to use Java's list methods.
- Print the list to show the original order of elements.
- Use Collections.sort on the list, which sorts the elements in case-sensitive order, prioritizing uppercase letters.
- At the end, we will print the sorted list to display the elements arranged in case-sensitive order.
Java program to sort a list in case-sensitive order
Below is the Java program to sort a list in case-sensitive order ?
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Demo { public static void main(String[] arg) throws Exception { String[] arr = new String[] { "P", "W", "g", "K", "H", "t", "E" }; Listlist = Arrays.asList(arr); System.out.println("List = " + list); Collections.sort(list); System.out.println("Case Sensitive Sort = " + list); } }
Output
List = [P, W, g, K, H, t, E] Case Sensitive Sort = [E, H, K, P, W, g, t]
Code explanation
The above program begins by creating an array of strings that includes both uppercase and lowercase letters. We then convert this array into a list using Arrays.asList, which allows us to use the Collections.sort method for sorting. Since the default behavior of Collections.sort is case-sensitive, it automatically arranges the list such that uppercase letters appear before lowercase ones. Finally, the sorted list is printed, showing the elements in case-sensitive order.