根据另一个数组对对象的 ArrayList 进行排序

Sort ArrayList of Objects based on another array

我想使用 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)中实现相同的内容

我建议使用:

    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);