I have a string array, in the first dimension are letters, in the second numbers, I wanted to sort by the numbers in the second dimension, the problem is that I have problems because the same number occurs several times, in the numbers that do not occur twice, it is sorted correctly, from the moment where a double number occurs, not.At least I have with a comporator the problen
I tried this, to sort, with this comparator method:
public static void main(String[] args) {
String[][] test = new String[5][2];
test[0][0] = "a";
test[1][0] = "a";
test[2][0] = "a";
test[3][0] = "a";
test[4][0] = "a";
test[0][1] = "1";
test[1][1] = "2";
test[2][1] = "1";
test[3][1] = "3";
test[4][1] = "4";
Comparator<String[]> test2 = new Comparator<String[]>() {
@Override
public int compare(String[] o1, String[] o2) {
if (Integer.parseInt(o1[1]) > Integer.parseInt(o1[1])) {
return 1;
} else if (Integer.parseInt(o1[1]) < Integer.parseInt(o1[1])) {
return -1;
} else {
return 0;
}
}
};
Arrays.sort(test, test2);
for (String[] t : test) {
System.out.println(t[1]);
}
}
The output is:
1
2
1
3
4
Same numbers makes problems... With out a same number correctly
1
2
3
4 would be the output...
(correct output from the example needed to be:
1
1
2
3
4
)
CodePudding user response:
This yields the correct output:
String[][] sorted = Arrays.stream(test)
.sorted(Comparator.comparingInt(a -> Integer.parseInt(a[1])))
.toArray(String[][]::new);
How it works should be pretty self explanatory, if something is unclear let me know and i can clarify.
If u just want to modify the existing array then:
Arrays.sort(test, Comparator.comparingInt(a -> Integer.parseInt(a[1])));
The issue in ur existing code was that u weren't using o2, so the comparisons didn't really make any sense.
The working version would be be:
Comparator<String[]> test2 = new Comparator<String[]>() {
@Override
public int compare(String[] o1, String[] o2) {
if (Integer.parseInt(o1[1]) > Integer.parseInt(o2[1])) {
return 1;
} else if (Integer.parseInt(o1[1]) < Integer.parseInt(o2[1])) {
return -1;
} else {
return 0;
}
}
};
Which is equivalent to:
Comparator<String[]> test2 = (o1, o2) -> {
return Integer.compare(Integer.parseInt(o1[1]), Integer.parseInt(o2[1]));
};
Simplified even more:
Comparator<String[]> test2 = Comparator.comparingInt(o -> Integer.parseInt(o[1]));