2

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()] }
7
  • 1
    pls, use proper data classes as examples. variables are written in lowercase in Kotlin. Commented Nov 16, 2020 at 9:38
  • See also: stackoverflow.com/questions/45349293/… Commented Nov 16, 2020 at 9:51
  • Hi Willi, thanks i gave it a try but ran into two issues, it was asking me to make the IDs public from private to access it (present in ModelClass) and I was unable to pass the final output to the useradapter as it was not a Users List but a Message List... how would you go about it? Commented Nov 16, 2020 at 10:28
  • hi hotkey, thanks, I did refer to that but ran into issue with declaring ID's as public and it didnt compute as the final output was of a different list type... Commented Nov 16, 2020 at 10:29
  • 1
    yup, the link to the extended question stackoverflow.com/questions/64861151/… Commented Nov 17, 2020 at 2:00

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.