为了账号安全,请及时绑定邮箱和手机立即绑定

根据字段与字符串列表的比较对对象列表进行排序

根据字段与字符串列表的比较对对象列表进行排序

眼眸繁星 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"); 我需要根据 list1 对列表进行排序。我的输出将是[Student [name=bcd,town=ytown],  Student [name=cdf,town=xtown],  Student [name=fgh,town=Atown],  Student [name=abc,town=xtown]]
查看完整描述

3 回答

?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

像这样使用java 8怎么样:

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


查看完整回答
反对 回复 2022-09-07
?
达令说

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


查看完整回答
反对 回复 2022-09-07
?
当年话下

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


查看完整回答
反对 回复 2022-09-07
  • 3 回答
  • 0 关注
  • 112 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号