Header Ads Widget

Responsive Advertisement

Sorting of name with upper case and lower case wise

Sorting names such that uppercase names appear first and are sorted alphabetically, followed by lowercase names sorted alphabetically, can be achieved by assigning weights or using a mathematical formula to prioritize uppercase over lowercase.

Here’s an approach:

Math-based Formula

You can use ASCII values to determine the sort order:

  1. ASCII values of uppercase letters (A-Z) range from 65 to 90.
  2. ASCII values of lowercase letters (a-z) range from 97 to 122.

To sort:

Ø  Calculate a "weight" for each string:

ü  For uppercase names, use a smaller weight (e.g., 1).

ü  For lowercase names, use a larger weight (e.g., 2).

Ø  Then sort based on this weight and alphabetically within groups.


Example Code

java

import java.util.*;

 

public class SortNames {

    public static void main(String[] args) {

        List<String> names = Arrays.asList("alice", "Bob", "charlie", "ALAN", "BOB", "david", "Amy");

 

        // Sort names: Uppercase first, then lowercase

        List<String> sortedNames = names.stream()

            .sorted((name1, name2) -> {

                // Calculate weights: 1 for uppercase, 2 for lowercase

                int weight1 = Character.isUpperCase(name1.charAt(0)) ? 1 : 2;

                int weight2 = Character.isUpperCase(name2.charAt(0)) ? 1 : 2;

 

                // Compare weights first

                if (weight1 != weight2) {

                    return Integer.compare(weight1, weight2);

                }

 

                // If weights are equal, compare names alphabetically

                return name1.compareTo(name2);

            })

            .toList();

 

        System.out.println("Sorted names: " + sortedNames);

    }

}

 


Explanation

  1. Weight Calculation:

Ø  Use Character.isUpperCase to check if the first character of the name is uppercase.

Ø  Assign 1 to uppercase names and 2 to lowercase names.

  1. Sorting Logic:

Ø  Sort by weights first (Integer.compare(weight1, weight2)).

Ø  For names with equal weights, use name1.compareTo(name2) to sort alphabetically.


Output

For the input list:

text

["alice", "Bob", "charlie", "ALAN", "BOB", "david", "Amy"]

 

The output will be:

Text

[ALAN, Amy, BOB, Bob, alice, charlie, david]

 


Why Math-Based?

The Character.isUpperCase method effectively distinguishes between uppercase and lowercase based on ASCII ranges, and the sort order is influenced mathematically by assigning weights.

You can further customize the formula if specific patterns or additional priorities are needed.

 

 


Second Approach:

 

To sort a list in Java such that uppercase elements appear first in sorted order followed by lowercase elements also in sorted order, you can use a custom comparator. Here’s how you can achieve this:

  1. Sort by Case: Ensure uppercase elements come before lowercase elements.
  2. Sort Alphabetically: Sort elements alphabetically within their case group.

Java Code Implementation

Here's how you can implement the custom sorting logic:

java

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.List;

 

public class CustomSort {

 

    // Custom comparator to sort by case and then alphabetically

    public static Comparator<String> customComparator() {

        return (s1, s2) -> {

            boolean s1UpperCase = Character.isUpperCase(s1.charAt(0));

            boolean s2UpperCase = Character.isUpperCase(s2.charAt(0));

 

            if (s1UpperCase && !s2UpperCase) {

                return -1;

            } else if (!s1UpperCase && s2UpperCase) {

                return 1;

            } else {

                return s1.compareTo(s2);

            }

        };

    }

 

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();

        list.add("apple");

        list.add("Banana");

        list.add("cherry");

        list.add("Apricot");

        list.add("banana");

        list.add("Cherry");

        list.add("apricot");

 

        // Sort the list using the custom comparator

        Collections.sort(list, customComparator());

 

        // Print the sorted list

        for (String s : list) {

            System.out.println(s);

        }

    }

}

 

Explanation

  1. Custom Comparator: The customComparator method returns a Comparator<String> that:

Ø  Checks the case of the first character of the strings.

Ø  If one string is uppercase and the other is lowercase, it ensures the uppercase string comes first.

Ø  If both strings are of the same case, it sorts them alphabetically.

  1. Main Method:

Ø  Creates a list of strings.

Ø  Sorts the list using Collections.sort with the custom comparator.

Ø  Prints the sorted list.

Output

For the provided list, the sorted output will be:

Apricot

Banana

Cherry

apple

apricot

banana

cherry

 

Conclusion

This program demonstrates how to sort a list in Java such that uppercase elements appear first, followed by lowercase elements, with each group sorted alphabetically. Adjust the list in the main method to test with different inputs.




Sorting of name with upper case and lower case
Sorting of name with upper case and lower case

For More DSA Related information, visit

Ø  Bench mark of compiler using Ackerman function

Ø  Find the Missing Number

Ø  To check if the rows of a matrix are circularly identical in Java

Ø  how to check loop in array

Ø  100 door puzzle programs

Ø  Frequency Weaving Logic & Spiral Printing of a Rectangle

Ø  Zig Zag Matrix print multiple way

Ø  Gready Algorithm’s or knapsack algorithms

Ø  understanding recursive method for binary tree

Ø  Dynamic Programming: Max Square Sub-matrix of 1s in a Matrix

Ø  Previous and Next Date Palindrome

Ø  Karatsuba's Algorithm for multiplying two large numbers

Ø  Multiplication In different Way

Ø  Division by Different way

Ø  Time Analysis for Congested Routes Using Shortest Path Algorithms

Ø  Sorting Of a list multiple attribute wise two technique

Ø  Seat Arrangement in Sorting Order Like 1A-1E, 3C-3G etc

 

For More Java Related information, visit

Ø  Streams Lambdas Collectors and Functional Interfaces in Java 8

Ø  Java 8 support static method or default method or both in the interface

Ø  Inheritance Understand

Ø  Serialization understanding

Ø  Clone Under standing

Ø  Exception understanding

Ø  Garbage Collection Under Standing

Ø  How work Garbage Collection in Java

Ø  Under Standing Of Mutable and Immutable Class

Ø  enum understand

 

For Other information, visit

Ø  How to get the neighbor of binary tree

Ø  OWASP (Open Web Application Security Project)

Ø  Mastering Debounce, Throttle, Rate Limit & Backoff in Java

Ø  How to draw sequence diagram and other diagrams using plantuml

Ø  Pascal Triangle

Ø  Molecular weight of chemistry in Java code

Ø  String to xml or html Beautifier

Ø  Key Components of Apache Kafka for Scalable Messaging

Ø  Build a Video Stream Microservice with Kafka & REST API in Java

Ø  Kafka general questions and answers

Post a Comment

0 Comments