我需要对Person
个对象的列表进行排序(List<Person>
,其中每Person
个对象都有一些属性,比如id
(唯一)、name
、age
……等等).
The sorting order is based on another list. That list contains a set of Person
id
's (A List<String>
which is already sorted).
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,..),…..
}
Ordered Id List :
List of ID {(“ID2”), (“ID1”),(”ID3”)….}
Sorted Person
list should be:
List PERSON {
(“ID-2”,”PERSON 2”,20,..) ), (“ID1”,”PERSON 2”,22,..), (“ID-3”,”PERSON 2”,19,..),…..
}
如果Person
列表包含id
列表中未提及的任何id
,则这些值应位于排序列表的末尾.
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;
}