madhall
madhall

Reputation: 182

Kotlin: Sort list based on another list (different objects)

I have two list, with the same no of items

List1 {id, timestamp} - Different dataClass

List2 {id, name, designation, profileimage} - different Dataclass

I need to order List2, in the order it's id's appear in List1? How can I achieve this?

I tried the below but got the following error on for

{ List3[it.getUID()] } 

"Type inference failed. The value of the type parameter K should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly."

val List3 = List1!!.withIndex().associate { it.value to it.index }
val List4 = (List2 as ArrayList<Users>).sortedBy { List3[it.getUID()] }

Upvotes: 2

Views: 2867

Answers (1)

Willi Mentzel
Willi Mentzel

Reputation: 29844

The easiest approach would be to first create a mapping of the list you want to sort by. It should associate the id to the actual object.

Then you iterate the list you want to sort by and map it's values to the object you retrieved from the mapping you just created.

Here a minimal example:

// 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)

Result:

[Bar(id=4), Bar(id=2), Bar(id=1), Bar(id=3)]

Upvotes: 7

Related Questions