JustanotherAlien
JustanotherAlien

Reputation: 27

Get List of specific Values form List of Maps in Kotlin

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?

Upvotes: 1

Views: 65

Answers (2)

Tarmo
Tarmo

Reputation: 4081

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"] }

Upvotes: 1

Ivo
Ivo

Reputation: 23164

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]

Upvotes: 6

Related Questions