【问题标题】:Android Kotlin: map or other equivalent of converting a List to a List of Pairs?Android Kotlin:映射或其他将列表转换为对列表的等价物?
【发布时间】:2021-09-20 06:29:18
【问题描述】:

假设我有这个:

listOf("ball","apple","zebra","cat")

我想把它转换成:

listOf(Pair("ball","b"),Pair("apple","a"),Pair("zebra","z"),Pair("cat","c"))

基本上我希望 Pair 的 second 是使用数组值计算的值。

我意识到我可以使用 for 循环的某些组合来创建它。但是有没有一种内置的方式使用类似于map 的一些函数来做到这一点?

【问题讨论】:

    标签: android arrays list kotlin


    【解决方案1】:

    你可以这样做:

     val mylist = listOf("ball","apple","zebra","cat")
     val pairList = mylist.map{
           Pair(it, it[0])
       }
     print(pairList)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      • 2021-02-16
      • 1970-01-01
      • 2011-10-23
      • 2022-08-15
      相关资源
      最近更新 更多