[FIXED] Sorting the List of Type Dto with List <String> contacting Ids in java

Issue

I have a List of objects like this:

List<Student> student= new ArrayList<Student>();

Student class looks like:

public class Student {
    private String Id;
    private String name;
}

I have another List<String> stuIds = new ArrayList<String>();

I want to sort student list based on stuIds list.

Tried this, but not getting the right order:

student.forEach(Id -> {
            
    student.sort(Comparator.comparing(items->stuIds.indexOf(student.getId())));     
});

AND

Collections.sort(student, 
    Comparator.comparing(item -> stuIds.indexOf(item)));
});

Is the sorting not happening because it is List<Dto> and List<String>? Could someone help here?

Solution

stuIds.indexOf(item) will always return -1 since item is a Student and stuIds contains Strings.

Try:

Collections.sort(student, 
    Comparator.comparing(item -> stuIds.indexOf(item.getID())));
});

Answered By – Eran

Answer Checked By – Marie Seifert (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published