Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List Kotlin:基于另一个列表(不同对象)对列表进行排序_List_Sorting_Kotlin - Fatal编程技术网

List Kotlin:基于另一个列表(不同对象)对列表进行排序

List Kotlin:基于另一个列表(不同对象)对列表进行排序,list,sorting,kotlin,List,Sorting,Kotlin,我有两个清单,项目数量相同 List1{id,timestamp}不同的数据类 List2{id,name,designation,profileimage}不同的数据类 我需要订购列表2,它的id在列表1中出现的顺序?我怎样才能做到这一点 我尝试了下面的方法,但在上出现以下错误 { List3[it.getUID()] } “类型推断失败。类型参数K的值应为 在输入类型(参数类型、接收器类型或预期)中提到 类型)。请尝试显式指定它。“ val List3=List1!!。withIndex

我有两个清单,项目数量相同

List1{id,timestamp}不同的数据类

List2{id,name,designation,profileimage}不同的数据类

我需要订购列表2,它的id在列表1中出现的顺序?我怎样才能做到这一点

我尝试了下面的方法,但在上出现以下错误

{ List3[it.getUID()] } 
“类型推断失败。类型参数K的值应为 在输入类型(参数类型、接收器类型或预期)中提到 类型)。请尝试显式指定它。“

val List3=List1!!。withIndex()。将{it.value与it.index}关联
val List4=(List2作为ArrayList).sortedBy{List3[it.getUID()]}

最简单的方法是首先创建要排序的列表的映射。它应该将id与实际对象相关联

然后迭代要排序的列表,并将其值映射到刚创建的映射中检索到的对象

这里有一个简单的例子:

// both can have more properties of course
data class Foo(val id: Int) 
data class Bar(val id: Int)

val fooList = listOf(Foo(4), Foo(2), Foo(1), Foo(3))
val barList = listOf(Bar(1), Bar(2), Bar(3), Bar(4))

val idValueMap = barList.associateBy { it.id }

val sortedByOtherList = fooList.map { idValueMap[it.id] }

println(sortedByOtherList)
结果:

[酒吧(id=4)、酒吧(id=2)、酒吧(id=1)、酒吧(id=3)]


请使用适当的数据类作为示例。变量在Kotlin中以小写形式编写。另请参见:Hi Willi,谢谢我尝试了一下,但遇到了两个问题,它要求我将ID从private设置为public以访问它(在ModelClass中显示),我无法将最终输出传递给useradapter,因为它不是用户列表,而是消息列表。。。你会怎么做?完成了,谢谢威利!是的,延伸问题的链接
// both can have more properties of course
data class Foo(val id: Int) 
data class Bar(val id: Int)

val fooList = listOf(Foo(4), Foo(2), Foo(1), Foo(3))
val barList = listOf(Bar(1), Bar(2), Bar(3), Bar(4))

val idValueMap = barList.associateBy { it.id }

val sortedByOtherList = fooList.map { idValueMap[it.id] }

println(sortedByOtherList)