1

I have a list of strings like this :-

listOf("abc", "a", "bb", "aa", "aaa", "bb", "a")

I want an output like this :-

listOf("a", "a", "aa", "bb", "bb", "aaa", "abc")

First I want to sort list by length and then again sort that length group by letters.

I tried below code so far

fun main() {
    val result = listOf("abc", "a", "bb", "aa", "aaa", "bb", "a").groupBy { it.length }
    val valueList = ArrayList(result.values).flatMap { it.toList() }
    println(valueList)
}

But the result I got is like below

[abc, aaa, a, a, bb, aa, bb]

After @Sergey Lagutin's duplication comment I also tried

val sortedList = a.sortedWith(compareBy { it.length })

Which is not returning the desired result

Mahesh Babariya
  • 4,560
  • 6
  • 39
  • 54
  • Possible duplicate of [How to sort based on/compare multiple values in Kotlin?](https://stackoverflow.com/questions/33640864/how-to-sort-based-on-compare-multiple-values-in-kotlin) – Sergii Lagutin Feb 06 '19 at 09:46
  • The example from [here](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/natural-order.html) should work. – TiiJ7 Feb 06 '19 at 09:52
  • The original problem in the code was that `groupBy` function returns an unsorted Map, so `result.values` has to be sorted by key values first. There is no need to wrap `result.values` with ArrayList – Eugene Petrenko Feb 06 '19 at 10:03

3 Answers3

2
val a = listOf("abc", "a", "bb", "aa", "aaa", "bb", "a")
a.sortedWith(compareBy({ it.length }, { it })) // [a, a, aa, bb, bb, aaa, abc]
Sergii Lagutin
  • 10,561
  • 1
  • 34
  • 43
1

You can try this way

val yourList = listOf("abc", "a", "bb", "aa", "aaa", "bb", "a")
val yourSortedList = yourList.sorted().sortedBy { it.length }
  • sorted will sort you list according to their natural sort order. In this case it will be alphabetic order.
  • With sortyBy you precise that the sort order is the length of your string.

Result [a, a, aa, bb, bb, aaa, abc]

Nicolas Duponchel
  • 1,219
  • 10
  • 17
0

Use sortedWith function on the collection

val a = listOf("abc", "a", "bb", "aa", "aaa", "bb", "a")
val b = a.sortedWith(compareBy({ it.length }, { it }))
println(b)
Eugene Petrenko
  • 4,874
  • 27
  • 36