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?
CodePudding user response:
stuIds.indexOf(item)
will always return -1
since item
is a Student
and stuIds
contains String
s.
Try:
Collections.sort(student,
Comparator.comparing(item -> stuIds.indexOf(item.getID())));
});
CodePudding user response:
There are two approaches to solving this problem:
Approach 1: Using a HashMap for fast sorting
This will take extra space
but will be faster
than normal sorting for your scenario:
List<Student> student = new ArrayList<Student>();
List<String> stuIds = new ArrayList<String>();
HashMap<String, Student> stringStudentHashMap = new HashMap<>();
for (Student student1 : student) {
stringStudentHashMap.put(student1.getId(), student1);
}
ArrayList<Student> sortedStudent = new ArrayList<>();
for (String stuId : stuIds) {
sortedStudent.add(stringStudentHashMap.get(stuId));
}
Approach 2: Using java Comparator:
You are not able to get the required result because you are trying to get the index of the Student
object (instead of studentId
) in the studentId
List. Try changing the code with below code:
Collections.sort(student,Comparator.comparing(t -> stuIds.indexOf(t.getId())));