Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort TreeMap by key using order CASE_INSENSITIVE_ORDER

Tags:

java

How can I sort a TreeMap<String, String> in CASE_INSENSITIVE_ORDER based on key.

Currently, by default, it is sorted like:

A B C D a b c d

I want it to be like:

a A b B c C d D

like image 460
reiley Avatar asked Nov 01 '25 15:11

reiley


2 Answers

The String.CASE_INSENSITIVE_ORDER - comparator does not sort as required in the question. The result that was asked for was an order like

a, A, b, B ...

Instead it handles "a" and "A" as "equal", which means an entry with key "a" would override an entry with the key "A" in the sorted-map. The outcome would rather be something like "a, B", depending on what was added to the map last.

One way to achieve the behaviour would be to use a custom-comparator like this:

Comparator<String> comparator = new Comparator<String>() {

    public int compare(String s1, String s2) {
        int n1 = s1.length();
        int n2 = s2.length();
        int min = Math.min(n1, n2);
        for (int i = 0; i < min; i++) {
            char c1 = s1.charAt(i);
            char c2 = s2.charAt(i);
            if (c1 != c2) {
                if (isAtoZ(c1) && isAtoZ(c2)) {
                    return getSortPosition(c1) - getSortPosition(c2);
                }
                return c1 - c2;
            }
        }
        return n1 - n2;
    }


    private boolean isAtoZ(char c) {
        return c > 64 && c < 123;
    }

    private int getSortPosition(char c) {
        if (c < 91) {
            // upper case
            return 2 * (c - 64); // A = 2, B = 4 ...
        } else if (c > 96) {
            // lower case
            return (2 * (c - 96)) - 1; // a = 1, b = 3 ...
        } else {
            // between Z and a: [, /, ], ^, _, `
            return c; // higher than the value for 'z'
        }
    }

};
like image 179
johannesv Avatar answered Nov 04 '25 07:11

johannesv


You can pass the case insensitive order comparator as the argument of one of TreeMap's constructors:

TreeMap<String, String> treemap = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
like image 28
andersschuller Avatar answered Nov 04 '25 06:11

andersschuller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!