面试题答案
一键面试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")
}
上述代码实现了以下功能:
- 统计最内层List元素个数:在处理每个内层
List
时,统计其元素个数并累加到count
变量中。 - 降序排序:当某个内层
List
元素个数大于10时,对该List
进行降序排序。 - 返回处理后的数据结构:最后返回处理后的整个数据结构,并打印出最内层
List
元素的总个数。