3 回答

TA贡献1895条经验 获得超7个赞
像这样使用java 8怎么样:
list.sort(Comparator.comparing(Student::getName, Comparator.comparing(list1::indexOf)));

TA贡献1821条经验 获得超6个赞
虽然YCF_L的答案可能是最优雅的,但我觉得一个更简单易懂的解决方案可以用于原始海报,这里有一个
首先,创建一个与要排序的列表大小相同的列表,并将所有元素初始化为 null:
List<Student> sortedList = new ArrayList<>(Collections.nCopies(list.size(), null));
然后,浏览您的学生列表并将其添加到正确的索引中
使用一个简单的循环:for
int index;
for(Student student : list) {
index = list1.indexOf(student.getName());
sortedList.set(index, student);
}
或者使用 :forEach
list.forEach(student -> {
int index = list1.indexOf(student.getName());
sortedList.set(index, student);
});
相应的单行:
list.forEach(s -> sortedList.set(list1.indexOf(s.getName()), s));

TA贡献1890条经验 获得超9个赞
您可以创建自己的自定义比较器。
Comparator<Student> comparator = new Comparator<Student>()
{
@Override
public int compare(Student o1, Student o2)
{
int index1 = list1.indexOf(o1.getName());
int index2 = list1.indexOf(o2.getName());
return Integer.compare(index1 , index2 );
}
};
和排序:)
java.util.Collections.sort(yourList, comparator);
添加回答
举报