3 回答

TA貢獻1895條經(jīng)驗 獲得超7個贊
像這樣使用java 8怎么樣:
list.sort(Comparator.comparing(Student::getName, Comparator.comparing(list1::indexOf)));

TA貢獻1821條經(jīng)驗 獲得超6個贊
雖然YCF_L的答案可能是最優(yōu)雅的,但我覺得一個更簡單易懂的解決方案可以用于原始海報,這里有一個
首先,創(chuàng)建一個與要排序的列表大小相同的列表,并將所有元素初始化為 null:
List<Student> sortedList = new ArrayList<>(Collections.nCopies(list.size(), null));
然后,瀏覽您的學生列表并將其添加到正確的索引中
使用一個簡單的循環(huán):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條經(jīng)驗 獲得超9個贊
您可以創(chuàng)建自己的自定義比較器。
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);
添加回答
舉報