Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make TreeMap work with Arrays as key?

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?

like image 941
auntyellow Avatar asked Dec 29 '17 07:12

auntyellow


Video Answer


2 Answers

Since java-9 this could be greatly simplified with :

 TreeMap<int[], String> map = new TreeMap<>(Arrays::compare);
like image 177
Eugene Avatar answered Oct 13 '22 14:10

Eugene


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;
    });
like image 36
Riaan Nel Avatar answered Oct 13 '22 14:10

Riaan Nel