简体   繁体   English

如何从第一个和第二个 position 手动从 Kotlin ZE84E30B9390CDB4864DZDB6C

[英]How to get object from 1st and 2nd position manually from LinkedHashMap in Kotlin Android?

See this LinkedHashMap看到这个 LinkedHashMap

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

So, from API this sizemap value I'm storing, but not sure how to retrieve it.所以,从 API 这个尺寸映射值我存储,但不知道如何检索它。 I checked and map size is coming 2.我查了一下,map 的尺寸是 2。

Without for loop, I manually want to get sizeMap[0] and sizeMap[1] and want to store in ProductSize object.如果没有 for 循环,我想手动获取 sizeMap[0] 和 sizeMap[1] 并希望存储在 ProductSize object 中。 But not able to do it.但做不到。

I tried below, but compiler error is coming in [0]我在下面尝试过,但编译器错误出现在 [0]

val sizeObj = it[0]

A LinkedHashMap is not a list, it is still a map. LinkedHashMap不是列表,它仍然是 map。 What you could do is你能做的是

sizeMap.values()[0]

First of all, sizeMap in your example is nullable.首先,您示例中的sizeMap可以为空。 You can't do anything with it before you make sure it is not null.在确定它不是 null 之前,你不能对它做任何事情。

Secondly, LinkedHashMap keeps ordering of elements, but that doesn't mean it allows to access its Nth element.其次, LinkedHashMap保持元素的顺序,但这并不意味着它允许访问其第 N 个元素。 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.幸运的是,Kotlin 提供了许多实用程序,可以在源代码中不进行实际迭代的情况下进行迭代。 For example, we can take first two values from the map like this:例如,我们可以从 map 中获取前两个值,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM