我想根据另一个具有不同值的数组对数组进行排序。 请考虑以下内容:
引用数组:{"A","B","C"}
获得的数组1:{"C","A","B"}
获得Array2:{"cc","aa","bb"}
获得Array3:{"123","asrd","sdhg"}
对应于
的值A -> aa and asrd
B -> bb and sdhg
C -> cc and 123
我想按引用数组指定的顺序对获得的数组1、2和3进行排序。
预期结果:
排序后获得数组:{"A","B","C"}
排序后获得Array2:{"aa","bb","cc"}
排序后获得Array3:{"asrd","sdhg","123"}
PS:引用数组元素的顺序可以是任何东西([A,B,C]
或[C,B,A
]等)。获得的数组2和3应该进行相应的排序。
我知道如何按照引用数组的顺序对获得的数组1进行排序。我尝试对所获得的数组2和3进行排序的逻辑,但是我得到的结果是错误的
String[] referenceArray = new String[] { "A", "B", "C" };
String[] obtainedArray1 = new String[] { "C", "A", "B" };
String[] obtainedArray2 = new String[] { "cc", "aa", "bb" };
String[] obtainedArray3 = new String[] { "123", "asrd", "sdhg" };
final List<String> referenceArrayList= Arrays.asList(referenceArray);
ArrayList<String> obtainedArray1_List= new ArrayList<String>(Arrays.asList(obtainedArray1));
ArrayList<String> obtainedArray2_List= new ArrayList<String>(Arrays.asList(obtainedArray2));
ArrayList<String> obtainedArray3_List= new ArrayList<String>(Arrays.asList(obtainedArray3));
// Sorting ObtainedArray1_List - This works Fine
Collections.sort(obtainedArray1_List, Comparator.comparing(s -> referenceArrayList.indexOf(s)));
//Sorting obtainedArray2_List - Not Working
Collections.sort(obtainedArray2_List, Comparator.comparing(s -> referenceArrayList.indexOf(obtainedArray1[obtainedArray2_List.indexOf(s)])));
排序后获得的array2_List的结果:["aa","cc","bb"]
预期结果为
["aa","bb","cc"]
答案 0 :(得分:0)
正如JB Nizet所说,您正在使生活变得复杂。您有三个单独的数组,而它们的内容是相关的。您是说A
,aa
和asrd
以及B
,bb
和sdhg
和{{1 }},C
和cc
。
可以将它们视为单个对象的三个属性。这就是面向对象的重点。您应该定义一个代表这三个属性的类:
123
您的三个数组最初不应存在,而应是包含public class Holder {
private String letter;
private String lower;
private String text;
public Holder(String letter, String lower, String text) {
this.letter = letter;
this.lower = lower;
this.text = text;
}
public String getLetter() {
return this.letter;
}
@Override
public String toString() {
return String.format("Holder(letter=%s, lower=%s, text=%s)",
this.letter, this.lower, this.text);
}
}
对象的数组或集合。为了方便起见,这里是对Holder
的转换。
List<Holder>
现在,您只需排序即可收集一个新的排序列表,而不是三个单独的排序数组。
List<Holder> holders = IntStream.range(0, obtainedArray1.length)
.mapToObj(i -> new Holder(obtainedArray1[i], obtainedArray2[i], obtainedArray3[i]))
.collect(Collectors.toList());