Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort ArrayList based on Another ArrayList in kotlin

I have a list of String as below:-

val a = listOf("G", "F", "E", "D", "C", "B", "A")

I will get another list from the server. For example:-

val b = listOf("A", "G", "C")

List from the server may contain fewer elements or more elements but will not contain elements other than the first list.

So, after sorting output should be like

// G, C, A

like image 895
Mahesh Babariya Avatar asked Jan 31 '26 03:01

Mahesh Babariya


2 Answers

You can use map and sorted to achieve that easily on the condition that a do not have repetition -

val a = listOf("G", "F", "E", "D", "C", "B", "A")
val b = listOf("A", "G", "C")
val there = b.map{ v -> a.indexOf(v)}.sorted().map{v -> a[v]}
println(there)

Output:: [G, C, A]

Alternate sorter way as pointed by @jsamol in comment -

val there = b.sortedBy { a.indexOf(it) }
like image 117
The_ehT Avatar answered Feb 01 '26 18:02

The_ehT


You are not trying to sort, you are trying to filter

fun filterByServer(server: List<String>, local: List<String>)
        = local.filter { value -> server.contains(value) }

filter takes a predicate in this case if your local value is contained on the server list

like image 38
cutiko Avatar answered Feb 01 '26 17:02

cutiko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!