Home > Mobile >  How to get object from 1st and 2nd position manually from LinkedHashMap in Kotlin Android?
How to get object from 1st and 2nd position manually from LinkedHashMap in Kotlin Android?

Time:12-17

See this LinkedHashMap

var sizeMap: LinkedHashMap<String, ProductSize>? = null

So, from API this sizemap value I'm storing, but not sure how to retrieve it. I checked and map size is coming 2.

Without for loop, I manually want to get sizeMap[0] and sizeMap[1] and want to store in ProductSize object. But not able to do it.

I tried below, but compiler error is coming in [0]

val sizeObj = it[0]

CodePudding user response:

A LinkedHashMap is not a list, it is still a map. What you could do is

sizeMap.values()[0]

CodePudding user response:

First of all, sizeMap in your example is nullable. You can't do anything with it before you make sure it is not null.

Secondly, LinkedHashMap keeps ordering of elements, but that doesn't mean it allows to access its Nth element. We still need to iterate over it to get an element at a specific index.

Fortunately, Kotlin provides many utils to make it possible to iterate without actual iterating in the source code. For example, we can take first two values from the map like this:

if (sizeMap != null) {
    val (first, second) = sizeMap.values.take(2)
}
  • Related