Home > Enterprise >  Kotlin fuction that has 2 parameters for sorting an Map or List
Kotlin fuction that has 2 parameters for sorting an Map or List

Time:11-09

I have a map that contains Keys and Values. i want to transfer it to a List and sort it by value first (integer) and then by Key (String) . This is , it sorts by value but if theres a tie in the value, i want to "untie" it by sorting it in Alphabetical order. Is there any kotlin , java function that does this? Thanks in advance

CodePudding user response:

The compareBy function creates a comparator from a sequence of functions returning comparable values. I think something along these lines should work:

val myList = myMap.toList()
    .sortedWith(compareBy( { it.second }, { it.first } ))
    .map { it.first }

P.S. Not sure what the list should contain in the end. If the pairs are desired instead of just the keys, remove the last line.

CodePudding user response:

There is a possibility to implement a comparator Comparator for Pair in Kotlin

This should work since yourMap.toList() is a list of Pairs. The only change that is required is to change the first and second comparator keys as follows (adapted from the first answer)

fun <T, U> pairComparator(
    firstComparator: Comparator<T>, 
    secondComparator: Comparator<U>
): Comparator<Pair<T, U>> = 
         compareBy(firstComparator) { p: Pair<T, U> -> p.second }
          .thenBy(secondComparator) { p: Pair<T, U> -> p.first }

CodePudding user response:

fun <T, U> pairComparator(
    firstComparator: Comparator<T>,
    secondComparator: Comparator<U>
): Comparator<Pair<T, U>> =
    compareBy(secondComparator) { p: Pair<T, U> -> p.second }
        .thenBy(firstComparator) { p: Pair<T, U> -> p.first }

list = list.sortedWith(pairComparator(naturalOrder(), reverseOrder()))

  • Related