-4

I want to sort arraylist of object based on another array using Java 7.

List A ={[id:1,name:"A"],[id:2,name:"B"],[id:3,name:"C"],[id:4,name:"D"]}

Array : {2,4}

Output: {[id:2,name:"B"],[id:4,name:"D"],[id:3,name:"C"],[id:1,name:"A"]}

Something same to the below question but need to implement the same in Java 7(without Lambda)

Sort ArrayList of Objects based on another array - Java

5
  • Then don't use lambda :)... imho, that's not similar... it's exactly the same. Commented Jun 20, 2018 at 6:25
  • Can you help with the solution without using lambda Commented Jun 20, 2018 at 6:27
  • I tried overriding the compare method..but no luck Commented Jun 20, 2018 at 6:29
  • You already got a working solution using Lambdas. Now all you need to do is understand what happens there and do it with Java 7 features... you should show that you attempted to solve your problem on your own over relying on us to port code for older Java-versions. Commented Jun 20, 2018 at 6:29
  • And then if you found a working solution for the problem without using any of the Java 8 features, also feel free to post it as an answer to your linked question so everyone who comes along that question can profit of it :) Commented Jun 20, 2018 at 6:31

1 Answer 1

1

I suggest using:

    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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.