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

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;
}

推荐答案

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

val orderById = ids.withIndex().associate { it.value to it.index }

然后按照id的顺序对people个列表进行排序:

val sortedPeople = people.sortedBy { orderById[it.id] }

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] })

Kotlin相关问答推荐

使数组变量在Kotlin中作为数组从意图传递到另一个活动

在intellij中使用kotlin符号和floordiv

插入/更新/upsert时不发出房间流

mutableStateOf 和 mutableStateListOf 有什么区别?

如何访问嵌套在另一个 map 中的 map 中的值(在 kotlin 中)

Kotlin 函数中接收者和参数的类型相同

Kotlin 启动与启动(Dispatchers.Default)

如何规避 Kotlin 的泛型类型差异约束

Kotlin 数据类中的大量参数

如果不为空,则为 builder 设置一个值 - Kotlin

在 SplashActivity 中显示的 Firebase 应用内消息.如何在 MainActivity 中显示它?

如何使用 gradle 脚本 Kotlin 构建文件构建可运行的 ShadowJar?

Kotlin 中的 Java Scanner 相当于什么?

Kotlin的web-framework框架

Kotlin解构when/if语句

添加抽象的私有getter和公共setter的正确方法是什么?

TypeConverter()在Android的TypeConverter错误中具有私有访问权限

Android Studio - java.io.IOException:无法生成 v1 签名

Kotlin 的数据类 == C# 的 struct ?

比较Kotlin的NaN