How to make TreeMap work with arrays as a key?

See a similar question: How to make HashMap work with arrays as a key?

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

My decision:

  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 have to write more.

Is there a way to generate a comparator for arrays of arbitrary length?

+5
source share
3 answers

A loop comparator should do the trick. Something like this if I understood your requirement correctly. It should be mentioned that all keys are assumed to have 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; }); 
+6
source

Since java-9 this can be greatly simplified with:

  TreeMap<int[], String> map = new TreeMap<>(Arrays::compare); 
+10
source

You can make a factory method that creates a comparator comparing the lengths of arrays and their values:

 public static Comparator<int[]> intArrayComparator(){ return ( left, right ) -> { int comparedLength = Integer.compare(left.length, right.length); if(comparedLength == 0){ for( int i = 0; i < left.length; i++ ){ int comparedValue = Integer.compare(left[i], right[i]); if(comparedValue != 0){ return comparedValue; } } return 0; } else { return comparedLength; } }; } 

What could you call the following:

 Map<int[], String> treeMap = new TreeMap<>(intArrayComparator()); 

The above comparator has the following cases:

  • Left more right: return 1
  • Left less than right: return -1
  • The element with index i in the left array is larger than one from the right array: return 1
  • The element with index i in the left array is less than one of the right array: return -1
  • From left to right is: return 0 ;
+1
source

Source: https://habr.com/ru/post/1274376/


All Articles