第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據(jù)字段與字符串列表的比較對對象列表進行排序

根據(jù)字段與字符串列表的比較對對象列表進行排序

眼眸繁星 2022-09-07 16:39:08
我有學生對象列表而 Student 對象具有public class Student{    private String name;    private String town;    // getters,setters and toString method}而我的長相是:List<Student>List<Student> list = new ArrayList<Student>();list.add(new Student("abc","xtown"));list.add(new Student("bcd","ytown"));list.add(new Student("cdf","xtown"));list.add(new Student("fgh","Atown"));另一個列表是List<String> list1 = new ArrayList<>();list1.add("bcd");list1.add("cdf");list1.add("fgh");list1.add("abc"); 我需要根據(jù) list1 對列表進行排序。我的輸出將是[Student [name=bcd,town=ytown],  Student [name=cdf,town=xtown],  Student [name=fgh,town=Atown],  Student [name=abc,town=xtown]]
查看完整描述

3 回答

?
人到中年有點甜

TA貢獻1895條經(jīng)驗 獲得超7個贊

像這樣使用java 8怎么樣:

list.sort(Comparator.comparing(Student::getName,
                               Comparator.comparing(list1::indexOf)));


查看完整回答
反對 回復 2022-09-07
?
達令說

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


查看完整回答
反對 回復 2022-09-07
?
當年話下

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


查看完整回答
反對 回復 2022-09-07
  • 3 回答
  • 0 關注
  • 130 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號