Kotlin 创建列表<列表<映射<字符串、字符串>>>



我正在尝试返回List<列表<映射<字符串,字符串>gt>来自科特林的一个活动。我是科特林的新手。

第1版

以下是我如何尝试这个

val a = mutableListOf(mutableListOf(mutableMapOf<String, String>()))

上述变量的问题是,我不知道如何将数据插入该变量。我试过这个:

val a = mutableListOf(mutableListOf(mutableMapOf<String, String>()))
val b = mutableListOf(mutableMapOf<String, String>())
val c = mutableMapOf<String, String>()
c.put("c", "n")
b.add(c)
a.add(b)

这给了我:

[[{}], [{}, {c=n}]]

我想要的是[[{c=n}]]

有人能告诉我如何在其中插入数据吗?

我试图实现的最终目标是以List<列表<映射<字符串,字符串>gt>

编辑2

我试图为其编写此数据结构的函数:

fun processReport(file: Scanner): MutableList<List<Map<String, String>>> {
val result = mutableListOf<List<Map<String, String>>>()
val columnNames = file.nextLine().split(",")
while (file.hasNext()) {
val record = mutableListOf<Map<String, String>>()
val rowValues = file.nextLine()
.replace(",(?=[^"]*"[^"]*(?:"[^"]*"[^"]*)*$)".toRegex(), "")
.split(",")
for (i in rowValues.indices) {
record.add(mapOf(columnNames[i] to rowValues[i]))
print(columnNames[i] + " : " + rowValues[i] + "   ")
}
result.add(record)
}
return result
}

您不需要使用可变的数据结构。你可以这样定义它:

fun main() {
val a = listOf(listOf(mapOf("c" to "n")))
println(a)
}

输出:

[[{c=n}]]

如果你想使用可变的数据结构并在以后添加数据,你可以这样做:

fun main() {
val map = mutableMapOf<String, String>()
val innerList = mutableListOf<Map<String, String>>()
val outerList = mutableListOf<List<Map<String, String>>>()
map["c"] = "n"
innerList.add(map)
outerList.add(innerList)
println(outerList)
}

输出是相同的,尽管列表和映射是可变的。


响应第二次编辑。啊,你正在解析CSV。你不应该自己去做,但你应该使用图书馆。下面是一个使用Apache Commons CSV 的示例

fun processReport(file: File): List<List<Map<String, String>>> {
val parser = CSVParser.parse(file, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader())
return parser.records.map {
it.toMap().entries.map { (k, v) -> mapOf(k to v) }
}
}

对于以下CSV:

foo,bar,baz
a,b,c
1,2,3

它产生:

[[{foo=a}, {bar=b}, {baz=c}], [{foo=1}, {bar=2}, {baz=3}]]

注意,如果你很乐意返回地图列表,你可以进一步简化它:

fun processReport(file: File): List<Map<String, String>> {
val parser = CSVParser.parse(file, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader())
return parser.records.map { it.toMap() }
}

输出:

[{foo=a, bar=b, baz=c}, {foo=1, bar=2, baz=3}]

我在这里使用Charset.defaultCharset(),但您应该将其更改为CSV所在的任何字符集。

最新更新