The purpose of a TreeMap
is to have an ordered collection
A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
You must pass a Comparator
that deals with int[][]
; here an example with one that sorted based on the full sum of the array
class Custom2DArrayComparator implements Comparator<int[][]> {
private static int sum(int[][] v) {
return Arrays.stream(v).map(arr -> Arrays.stream(arr).sum())
.mapToInt(Integer::intValue).sum();
}
@Override
public int compare(int[][] o1, int[][] o2) {
return Integer.compare(sum(o1), sum(o2));
}
}
Use
public static void main(String[] args) {
TreeMap<int[][], Integer> tempMap = new TreeMap<>(new Custom2DArrayComparator());
int[][] matrix = {{1}};
tempMap.put(matrix, 4);
}
You can use the anonymous class to avoid creating a one outside
public static void main(String[] args) {
TreeMap<int[][], Integer> tempMap = new TreeMap<>(new Comparator<>() {
@Override
public int compare(int[][] o1, int[][] o2) {
return Integer.compare(sum(o1), sum(o2));
}
int sum(int[][] v) {
return Arrays.stream(v).map(arr -> Arrays.stream(arr).sum())
.mapToInt(Integer::intValue).sum();
}
});
int[][] matrix = {{1}};
tempMap.put(matrix, 4);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…