将数组映射到对象kotlin列表 [英] Mapping arrays to list of objects kotlin
问题描述
我想知道将多个数组映射到一个对象列表的方法.
I'm wondering about methods of mapping multiple arrays into one list of object.
我的意思是我有
val a = arrayOf("A1","A2","A3")
val b = arrayOf("B1","B2","B3")
和
data class SomeClass(val v1:String, val v2:String)
我想用一种优雅的方式来解析它,以获得这样的列表:
I want to parse it in elegant way to have list like that:
val list = listOf(SomeClass("A1","B1"),SomeClass("A2","B2"),SomeClass("A3","B3"))
我认为它们的长度相同.我想到的唯一方法是:
I assume they are of the same length. The only way I thought of is:
val list = mutableListOf<SomeClass>()
for (i in a.indices)
array.add(SomeClass(a[i],b[i])
是否有更好,更优雅的解决方案(也许使用Collecions.zip或Array.map)?
Is there a better, more elegant solution (maybe using Collecions.zip or Array.map)?
推荐答案
val list = a.zip(b)
.map { (a, b) -> SomeClass(a, b) }
请注意,如果两个数组的大小均不同,则其他值将被忽略.还要注意,这将创建中间Pair
(这是zip
的默认转换函数).尽管我更喜欢显式的map
,但有关重载方法的@hotkeys解决方案更合适(您可以保留隐藏的Pair
-transformation):
Note that if both arrays differ in size, the additional values are ignored. Note also that this will create intermediate Pair
s (which is the default transformation function of zip
). Even though I like the explicit map
more, @hotkeys solution regarding the overloaded method is more appropriate (you spare that hidden Pair
-transformation):
val list = a.zip(b) { a, b -> SomeClass(a, b) }
当使用引用代替时,重载方法可能发光的地方:
And where the overloaded method probably shines, is when using references instead:
a.zip(b, ::SomeClass)
只要您有一个与压缩参数匹配的构造函数,并且在Pair
范围内无法使用(还可以吗?),这将起作用.
Which will work as long as you have a constructor matching the zipped arguments and doesn't work out of the box for the Pair
(yet?).
这篇关于将数组映射到对象kotlin列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!