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?
Since java-9 this could be greatly simplified with :
TreeMap<int[], String> map = new TreeMap<>(Arrays::compare);
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With