基于将字段与字符串列表进行比较来对对象列表进行排序

问题描述 投票:2回答:3

我有学生对象列表

而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]]
java list sorting comparator
3个回答
1
投票

那么使用java 8怎么样:

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

1
投票

虽然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);
});

相应的One-liner:

list.forEach(s -> sortedList.set(list1.indexOf(s.getName()), s));

0
投票

您可以创建自己的自定义比较器。

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);
© www.soinside.com 2019 - 2024. All rights reserved.