根据另一个列表的顺序对列表进行排序 [英] Sorting list based on another list's order
问题描述
我需要对Person
个对象的列表进行排序(List<Person>
,其中每个Person
对象具有一些属性,例如id
(唯一),name
,age
…等).
I need to sort a list of Person
objects(List<Person>
, where each Person
object has few attributes like id
(unique), name
, age
… etc).
排序顺序基于另一个列表.该列表包含一组Person
id
(已排序的A List<String>
).
The sorting order is based on another list. That list contains a set of Person
id
's (A List<String>
which is already sorted).
使用Kotlin或Java以与id
列表相同的顺序订购List<Person>
的最佳方法是什么.
What is the best way to order the List<Person>
in the same order as the list of id
's using Kotlin or Java.
示例:
List Person {
("ID1","PERSON1",22,..), ("ID-2","PERSON2",20,..) ), ("ID-3","PERSON3",19,..),…..
}
订购的ID列表:
List of ID {("ID2"), ("ID1"),("ID3")….}
排序的Person
列表应为:
List PERSON {
("ID-2","PERSON 2",20,..) ), ("ID1","PERSON 2",22,..), ("ID-3","PERSON 2",19,..),…..
}
如果Person
列表包含id
列表中未提及的任何id
,则这些值应位于已排序列表的末尾.
If the Person
list contains any id
's which are not mentioned in the id
list then those values should be at the end of the sorted list.
这是我目前使用Java的方式.我希望有一个比这更好的方法:
Edited: This is my current way in Java. I am hoping for a better way than this:
public static List<Person> getSortList(List <Person> unsortedList, List<String> orderList){
if(unsortedList!=null && !unsortedList.isEmpty() && orderList!=null && !orderList.isEmpty()){
List sortedList = new ArrayList<OpenHABWidget>();
for(String id : orderList){
Person found= getPersonIfFound(unsortedList, id); // search for the item on the list by ID
if(found!=null)sortedList.add(found); // if found add to sorted list
unsortedList.remove(found); // remove added item
}
sortedList.addAll(unsortedList); // append the reaming items on the unsorted list to new sorted list
return sortedList;
}
else{
return unsortedList;
}
}
public static Person getPersonIfFound(List <Person> list, String key){
for(Person person : list){
if(person.getId().equals(key)){
return person;
}
}
return null;
}
推荐答案
一种有效的解决方案是首先创建从ids
中的ID(您所需的ID顺序)到该列表中的索引的映射:
An efficient solution is to first create the mapping from the ID in the ids
(your desired IDs order) to the index in that list:
val orderById = ids.withIndex().associate { it.value to it.index }
,然后在此映射中按id
的顺序对people
列表进行排序:
And then sort your list of people
by the order of their id
in this mapping:
val sortedPeople = people.sortedBy { orderById[it.id] }
注意:如果某人具有ids
中不存在的ID,则他们将被放置在列表的第一位.要将它们放置在最后,可以使用 nullsLast
比较器:
Note: if a person has an ID that is not present in the ids
, they will be placed first in the list. To place them last, you can use a nullsLast
comparator:
val sortedPeople = people.sortedWith(compareBy(nullsLast<String>) { orderById[it.id] })
这篇关于根据另一个列表的顺序对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!