Home > Software design >  Get List of specific Values form List of Maps in Kotlin
Get List of specific Values form List of Maps in Kotlin

Time:01-24

I have a Kotlin list, which consists of Maps:

allData = 
  [
    {
      "a":"some a Data1",
      "b":"some b Data1",
      "c":"some c Data1"
    },
    {
      "a":"some a Data2",
      "b":"some b Data2",
      "c":"some c Data2"
    },
    {
      "a":"some a Data3",
      "b":"some b Data3",
      "c":"some c Data3"
    }
  ]

Now I would like to get the List of all b-Data:

bData = ["some b Data1", "some b Data2", "some b Data3"]

How can I get bData from allData?

CodePudding user response:

You can do

val bData  = allData.map { it["b"] }

full example:

val allData = listOf(
    mapOf("a" to "some a Data1", "b" to "some b Data1", "c" to "some c Data1"),
    mapOf("a" to "some a Data2", "b" to "some b Data2", "c" to "some c Data2"),
    mapOf("a" to "some a Data3", "b" to "some b Data3", "c" to "some c Data3")
)

val bData  = allData.map { it["b"] }

print(bData )
//[some b Data1, some b Data2, some b Data3]

CodePudding user response:

val allData = listOf(mapOf("a" to "some a Data1", "b" to "some b Data1", "c" to "some c Data1"), mapOf("a" to "some a Data2", "b" to "some b Data2", "c" to "some c Data2"), mapOf("a" to "some a Data3", "b" to "some b Data3", "c" to "some c Data3"))

val result = allData.map { it["b"] }
  • Related