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 ;
source share