繁体   English   中英

用 List 对 Dto 类型的 List 进行排序<string> java 中的联系 ID</string>

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

我有一个这样的对象List

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

Student class 看起来像:

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

我有另一个List<String> stuIds = new ArrayList<String>();

我想根据stuIds列表对student列表进行排序。

试过这个,但没有得到正确的顺序:

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

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

排序没有发生,因为它是List<Dto>List<String>吗? 有人可以在这里帮忙吗?

stuIds.indexOf(item)将始终返回-1 ,因为itemStudent并且stuIds包含String s。

尝试:

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

有两种方法可以解决这个问题:

方法一:使用 HashMap 进行快速排序

这将占用额外的space ,但会比您的场景的正常排序faster

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

方法二:使用 java 比较器:

您无法获得所需的结果,因为您试图在studentId列表中获取Student object 的索引(而不是studentId )。 尝试使用以下代码更改代码:

Collections.sort(student,Comparator.comparing(t -> stuIds.indexOf(t.getId())));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM