Вот фрагмент кода, который должен вам помочь.Он сортирует массив в соответствии со строкой номер два в порядке, указанном a2.Если строки секунд совпадают, сравнивается первая строка, а затем третья строка.Следите за тем, чтобы он проверял наличие нулевых строк.
Важная часть:
@Override
public int compare(String[] o1, String[] o2) {
int score1 = types.indexOf(o1[1])-types.indexOf(o2[1]);
if(score1!=0) {
return score1;
}
int score2 = o1[0].compareTo(o2[0]);
if(score2!=0) {
return score2;
}
int score3 = o1[2].compareTo(o2[2]);
return score3;
}
См .:
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;
public class SpecialComparatorMain implements Comparator<String[]> {
private List<String> types;
public SpecialComparatorMain(List<String> types) {
this.types = types;
}
public static void main(String[] args) {
String[] a2 = new String[]{"dog","cat","monkey"};
String[][] a1 = new String[][]{
{"z","dog","x"},
{"y","monkey","x"},
{"x","cat","x"},
{"x","monkey","x"},
{"y","cat","x"},
{"z","monkey","z"},
{"z","monkey","y"},
{"z","monkey","x"},
};
//x being a random string
System.out.println("Before");
Stream.of(a1).map(Arrays::toString).forEach(System.out::println);
Arrays.sort(a1, new SpecialComparatorMain(Arrays.asList(a2)));
System.out.println("After");
Stream.of(a1).map(Arrays::toString).forEach(System.out::println);
}
@Override
public int compare(String[] o1, String[] o2) {
int score1 = types.indexOf(o1[1])-types.indexOf(o2[1]);
if(score1!=0) {
return score1;
}
int score2 = o1[0].compareTo(o2[0]);
if(score2!=0) {
return score2;
}
int score3 = o1[2].compareTo(o2[2]);
return score3;
}
}
Вывод:
Before
[z, dog, x]
[y, monkey, x]
[x, cat, x]
[x, monkey, x]
[y, cat, x]
[z, monkey, z]
[z, monkey, y]
[z, monkey, x]
After
[z, dog, x]
[x, cat, x]
[y, cat, x]
[x, monkey, x]
[y, monkey, x]
[z, monkey, x]
[z, monkey, y]
[z, monkey, z]
НТН!