根据另一个列表的顺序对列表进行排序

Nir*_*han 5 java sorting list kotlin

我需要对Person对象列表进行排序(List<Person>,其中每个Person对象都有一些属性,例如id(unique)nameage...等)。

排序顺序基于另一个列表。该列表包含一组Person idList<String>已排序的A )。

用Kotlin或Java List<Person>按照与列表相同的顺序订购的最佳方法是什么id

例:

List Person {
(“ID1”,”PERSON1”,22,..), (“ID-2”,”PERSON2”,20,..) ), (“ID-3”,”PERSON3”,19,..),…..
}
Run Code Online (Sandbox Code Playgroud)

订购ID清单:

List of ID {(“ID2”), (“ID1”),(”ID3”)….}
Run Code Online (Sandbox Code Playgroud)

排序Person列表应为:

List PERSON {
 (“ID-2”,”PERSON 2”,20,..) ), (“ID1”,”PERSON 2”,22,..),  (“ID-3”,”PERSON 2”,19,..),…..
}
Run Code Online (Sandbox Code Playgroud)

如果Person列表包含列表中id未提及的任何id值,则这些值应位于已排序列表的末尾。


编辑:这是我目前使用Java的方式。我希望有一个比这更好的方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

hot*_*key 9

一个有效的解决方案是首先创建从ids(按所需ID顺序)ID到该列表中索引的映射:

val orderById = ids.withIndex().associate { it.value to it.index }
Run Code Online (Sandbox Code Playgroud)

然后按照people它们id在此映射中的顺序对列表进行排序:

val sortedPeople = people.sortedBy { orderById[it.id] }
Run Code Online (Sandbox Code Playgroud)

注意:如果某人的ID在中不存在,则ids他们将被放在列表的第一位。要将它们放置在最后,可以使用nullsLast比较器:

val sortedPeople = people.sortedWith(compareBy(nullsLast<String>) { orderById[it.id] })
Run Code Online (Sandbox Code Playgroud)

  • 这里的“ nullsFirst”会影响空人的顺序,而不是影响“ orderById [id]”为空的人的顺序。要指定键的空顺序,您需要将一个可选的比较器传递给`compareBy`:`people.sortedWith(compareBy(nullsFirst &lt;Int&gt;()){orderById [it.id]})。该比较器是可选的,因为如果没有它,则将首先对null进行排序。 (2认同)