How to make TreeMap work with Arrays as key?

auntyellow :

Similar question see: How to make HashMap work with Arrays as key?

But I need TreeMap like ((int key1, int key2) -> String), comparing key1 then comparing key2.

My solution is:

    Map<int[], String> map = new TreeMap<>(Comparator.
            <int[]>comparingInt(key -> key[0]).thenComparingInt(key -> key[1]));

But when I need ((int key1, int key2, int key3) -> String, I must write more.

Is there a way to generate the Comparator for arrays with arbitrary length?

Riaan Nel :

A Comparator with a loop should do the trick. Something like this, if I understood your requirement correctly. I should mention that it assumes that all keys are of the same length.

    Map<int[], String> treeMap = new TreeMap<>((o1, o2) -> {
        for (int i = 0; i < o1.length; i++) {
            if (o1[i] > o2[i]) {
                return 1;
            } else if (o1[i] < o2[i]) {
                return -1;
            }
        }

        return 0;
    });

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=473208&siteId=1