hodokeg
hodokeg

Reputation: 9

Sort Kotlin arraylist based on values of another arraylist

arr[0] = Name(id=122, title="title0")
arr[1] = Name(id=123, title="title1")
arr[2] = Name(id=124, title="title2")
......

I need to sort it with below array

arrRef[0] = "title2"
arrRef[1] = "title0"
arrRef[2] = "title1"

Result:

arr[0] = Name(id=124, title="title2")
arr[1] = Name(id=122, title="title0")
arr[2] = Name(id=123, title="title1")
......

In java we do it like

Collections.sort(arrRef, Comparator.comparing(s -> arr[arrRef.indexOf(s)]));

Upvotes: 0

Views: 956

Answers (2)

Frank Neblung
Frank Neblung

Reputation: 3165

If your list of names is really long, you should hash the title to its index, because repeatedly invoking list.indexOf(value) performs poorly for long lists.

val names = arrayListOf(
    Name(122, "title0"),
    Name(123, "title1"),
    Name(124, "title2")
)

val titles = listOf(
    "title2",
    "title0",
    "title1"
)

val hash = titles.withIndex().associateTo(HashMap()) { it.value to it.index }

names.sortBy { hash[it.title] }

Upvotes: 1

Mirek Hýbler
Mirek Hýbler

Reputation: 51

i created two array lists with

   val arr = arrayListOf(
        Name(122, "title0"),
        Name(123, "title1"),
        Name(124, "title2")
    )

    val arrRef = arrayListOf(
        "title2",
        "title0",
        "title1"
    )

and sort the arr list with sortBy extension function

    arr.sortBy { name ->
        arrRef.indexOf(name.title)
    }

Upvotes: 1

Related Questions