MST
星途 面试题库

面试题:Kotlin集合操作与序列优化之专家难度题

有一个复杂的Kotlin数据结构,包含多层嵌套的集合(例如List<List<Map<String, List<Int>>>>)。请通过Kotlin集合操作与序列优化技巧,统计所有最内层List中元素的个数,并且当某个内层List元素个数大于10时,对该List进行降序排序,最后返回处理后的整个数据结构。
34.2万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试
fun processDataStructure(data: List<List<Map<String, List<Int>>>>): List<List<Map<String, List<Int>>>> {
    var count = 0
    return data.map { outerList ->
        outerList.map { map ->
            map.mapValues { entry ->
                count += entry.value.size
                if (entry.value.size > 10) {
                    entry.value.sortedDescending()
                } else {
                    entry.value
                }
            }
        }
    }.also { println("Total count of elements in innermost lists: $count") }
}

你可以这样调用这个函数:

fun main() {
    val complexData: List<List<Map<String, List<Int>>>> = listOf(
        listOf(
            mapOf("key1" to listOf(1, 2, 3), "key2" to listOf(4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14))
        ),
        listOf(
            mapOf("key3" to listOf(15, 16, 17), "key4" to listOf(18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28))
        )
    )
    val result = processDataStructure(complexData)
    println("Processed data structure: $result")
}

上述代码实现了以下功能:

  1. 统计最内层List元素个数:在处理每个内层List时,统计其元素个数并累加到count变量中。
  2. 降序排序:当某个内层List元素个数大于10时,对该List进行降序排序。
  3. 返回处理后的数据结构:最后返回处理后的整个数据结构,并打印出最内层List元素的总个数。