1

Let's say I have the following code:

val list = mutableListOf("abab", "abcd", "aaa")
list.sortBy { it.length } //result: [aaa, abab, abcd]

This sorts the list by the lengths of the Strings.

How do I break draws (2 Strings of the same length) by some other rule, lets say number of appearance of the char 'a'. This way, one would have a hirarchy of comparison-rules: First length, then break draws by number of 'a', then maybe some other rule.

The function sortBy only receives a selector, which maps the elements to a comparable value, which is not capable for what I want to do I think.

Moritz Groß
  • 1,352
  • 12
  • 30

1 Answers1

4

Use sortWith and a custom comparator

val list = mutableListOf("abab", "abcd", "aaa")
list.sortWith(compareBy(String::length).thenBy { it.count { char -> char == 'a'} })

Here you can see documentation for all functions that will help you create a new comparator: kotlin.comparisons

IR42
  • 8,587
  • 2
  • 23
  • 34
  • 2
    This is what I searched for. 1 improvement: `compareBy(String::length, { it.count { c -> c == 'a' } })` works aswell, because comparyBy takes vararg functions that are considered after each other to break draws. – Moritz Groß Jun 22 '20 at 12:25