在某些条件下更改列表元素的位置

问题描述 投票:1回答:3

我有这样的字符串列表: -

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

我想要这样的输出: -

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

首先,我想按长度对列表进行排序,然后再按字母对该长度组进行排序。

到目前为止我尝试了下面的代码

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)
}

但我得到的结果如下

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

在@Sergey Lagutin的重复评论之后我也试过了

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

哪个没有返回所需的结果

arraylist kotlin hashmap
3个回答
2
投票
val a = listOf("abc", "a", "bb", "aa", "aaa", "bb", "a")
a.sortedWith(compareBy({ it.length }, { it })) // [a, a, aa, bb, bb, aaa, abc]

1
投票

你可以试试这种方式

val yourList = listOf("abc", "a", "bb", "aa", "aaa", "bb", "a")
val yourSortedList = yourList.sorted().sortedBy { it.length }
  • 已排序将根据其自然排序顺序对您进行排序。在这种情况下,它将是字母顺序。
  • 使用sortyBy,您可以精确地确定排序顺序是字符串的长度。

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


0
投票

在集合上使用sortedWith函数

val a = listOf("abc", "a", "bb", "aa", "aaa", "bb", "a")
val b = a.sortedWith(compareBy({ it.length }, { it }))
println(b)
© www.soinside.com 2019 - 2024. All rights reserved.