我想使用Java 7根据另一个数组对对象的数组列表进行排序。
List A ={[id:1,name:"A"],[id:2,name:"B"],[id:3,name:"C"],[id:4,name:"D"]}
数组:{2,4}
输出:{[id:2,name:“ B”],[id:4,name:“ D”],[id:3,name:“ C”],[id:1,name:“ A“]}
与以下问题相同,但需要在Java 7(无Lambda)中实现相同
答案 0 :(得分:1)
我建议使用:
int[] index = {2, 4};
List<Model> modelList = new ArrayList<>(Arrays.asList(new Model(1, "a"),
new Model(2, "b"), new Model(3, "c"),
new Model(4, "d")));
Map<Integer, Model> modelMap = new HashMap<>();
for (Model model : modelList) {
modelMap.put(model.id, model);
}
// sort by index
modelList.clear();
for (int anIndex : index) {
modelList.add(modelMap.get(anIndex));
modelMap.remove(anIndex);
}
if (!modelMap.isEmpty()) {
for (Map.Entry<Integer, Model> entry : modelMap.entrySet()) {
modelList.add(entry.getValue());
}
}
System.out.println(modelList);