Skip to content
Related Articles

Related Articles

Java Program For Case Specific Sorting

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 04 Sep, 2021
Improve Article
Save Article

Given a string S consisting of uppercase and lowercase characters. The task is to sort uppercase and lowercase letters separately such that if the “i”th place in the original string had an Uppercase character then it should not have a lowercase character after being sorted and vice versa. it is described in the illustration as shown below:


Input : srbDKi 
Output: birDKs
Processing : After sorting we have to place the lowercase characters to the lowercase and uppercase character to specific uppercase character 


  1. We will use two ArrayList one to store the lowercase values and the second to store uppercase values.
  2. After adding elements into the lists we will sort the list using Collections.sort(list) method
  3. After sorting, we will traverse the string and check case-specific and store the element at the correct position



// Java Program for Case Specific Sorting
// using Collections.sort(list) method
// Importing input output classes
// Importing utility classes
import java.util.*;
class GFG {
    // Method 1
    // To sort the string
    static String sortString(String str)
        // Creating two Arraylist  class objects
        // Declaring object of character type
        ArrayList<Character> list = new ArrayList<>();
        ArrayList<Character> list2 = new ArrayList<>();
        // Initially the string is empty
        String res = "";
        // Iterating over the string
        for (int i = 0; i < str.length(); i++) {
            // Finding character at indexes
            // using charAt() method in List object
            if (str.charAt(i) >= 'a'
                && str.charAt(i) <= 'z')
            if (str.charAt(i) >= 'A'
                && str.charAt(i) <= 'Z')
        // Sorting the Collection interface
        // using sort() method
        int i = 0;
        int j = 0;
        // iterating over string using length() method
        for (int k = 0; k < str.length(); k++) {
            // If lowercase character encountered
            if (str.charAt(k) >= 'a'
                && str.charAt(k) <= 'z') {
                // Appending them all in beginning of string
                res += list.get(i);
            // If uppercase character encountered
            else if (str.charAt(k) >= 'A'
                     && str.charAt(k) <= 'Z') {
                // Appending them all together after
                // lowercase is finished in input string
                res += list2.get(j);
        return res;
    // Method 2
    // Main driver method
    public static void main(String[] args)
        // Passing the custom string as input for which we
        // want case-specific sorting by calling the method
        // 1 as defined above




My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!