猿问

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

我有学生对象列表


而 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]]


眼眸繁星
浏览 113回答 3
3回答

人到中年有点甜

像这样使用java 8怎么样:list.sort(Comparator.comparing(Student::getName, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Comparator.comparing(list1::indexOf)));

达令说

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

当年话下

您可以创建自己的自定义比较器。Comparator<Student> comparator = new Comparator<Student>(){&nbsp; &nbsp; @Override&nbsp; &nbsp; public int compare(Student o1, Student o2)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; int index1 = list1.indexOf(o1.getName());&nbsp; &nbsp; &nbsp; &nbsp; int index2 = list1.indexOf(o2.getName());&nbsp; &nbsp; &nbsp; &nbsp; return Integer.compare(index1 , index2 );&nbsp; &nbsp; }};和排序:)java.util.Collections.sort(yourList, comparator);
随时随地看视频慕课网APP

相关分类

Java
我要回答