2

I am a beginner in Java and I am having a problem sorting String. I know using Collections.sort it will sort String with case-sensitive by default but the uppercase ones always come in the front because it always compares the ASCII values.

If I want to keep lowercase String in front of uppercase ones, is there a clean way to implement it in Java using Collections.sort?

For example, to sort "java Python ruby C" into "java ruby C Python".

Thanks in advance.

4 Answers 4

4

You should implement your own Comparator to define such an ordering:

Collections.sort(list, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        if (/* s1 is lower case and s2 is upper case */) {
            return 1;
        }

        if (/* s1 is upper case and s2 is lower case */) {
            return -1;
        }

        return s1.compareTo(s2);
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks arshajii. One step further, if the words includes strings with all lowercase characters, all uppercase characters or uppercase in the first character only, do I need check one by one?
@Jimmy Yes, it would probably be best to check one by one.
0

Of course you can use a Comparator .Use Collections.sort(List<String> x,Comparator comp)

Comments

0

This is achieved by creating a Comparator that will impelemt the compare method.

Here is example of using AgeComparator:

import java.util.Comparator;

public class HeightComparator implements Comparator<Object> {

    @Override
    public int compare(Object o1, Object o2) {
        int p1 = ((Person)o1).height;
        int p2 = ((Person)o2).height;
        return p1 - p2;
    }
}

Now all that left is to pass our custom comparator with the collection we want to compare.

Collections.sort(peoples, new AgeComparator())

More on Comparators and Comparable can be read HERE.

1 Comment

Thanks. This is a good one too and I can use it for more complicated ones.
0

arshajii's answer is solid. Here're the two minor conditional statements:

Collections.sort(list, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        if (s1.toLowerCase().equals(s1) && s2.toUpperCase().equals(s2)) {
            return 1;
        }

        if (s1.toUpperCase().equals(s1) && s2.toLowerCase().equals(s2)) {
            return -1;
        }

        return s1.compareTo(s2);
    }
};

1 Comment

Thanks for the implementation here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.