简体   繁体   English

可变列表到 Kotlin 中的 HashMap

[英]MutableList to HashMap in Kotlin

I want to convert the value of MutableList to HashMap .我想将HashMap MutableList Can you help me with this?你能帮我解决这个问题吗? This is my code:这是我的代码:

private fun getDestinationFund(destinationFund: List<DestinationFundEntity>) {
        val list = mutableListOf<FundsModel>()
        for (i in destinationFund) {
            list.add(
                FundsModel(
                    ljiId = i.ljiId,
                    name = i.productName,
                    mduPercent = i.percentage
                )
            )
        }

        convertListToMap(list)
}
private fun convertListToMap(list: MutableList<FundsModel>) {
   val map: HashMap<String?, FundsModel> = HashMap()

   // Need to convert "list" from params to "map" from "val"

   // So, the Live data get data from "map", not from "list"
   _currentFundsList.postValue(ArrayList(map.values))
}

Fixed using this:使用此修复:

private fun convertListToMap(list: MutableList<FundsModel>) {
     val map: HashMap<String?, FundsModel> = HashMap()

     list.forEach {
         map[it.name] = it
     }

     _currentFundsList.postValue(ArrayList(map.values))
}

You can use List.map() to transform your list into a list of Pair s, and then use toMap() on that list:您可以使用List.map()将您的列表转换为Pair的列表,然后在该列表上使用toMap()

listOf(1,2,3,4)
  .map { it -> it to it * 2 }
  .toMap()

// produces: {1=2, 2=4, 3=6, 4=8}

暂无
暂无

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

相关问题 从 MutableList kotlin 中弹出 Mutablelist - Pop Mutablelist from a MutableList kotlin 在 Kotlin 中对 MutableList 中的数据进行排序 - Sort data from a MutableList in Kotlin 如何在Kotlin中复制MutableList? - How to make copy of MutableList in Kotlin? 可变列表<object>方法中的变量(Kotlin)<div id="text_translate"><p> 有没有办法生成多个对象的数组?</p><p> 我想要这样的东西:</p><pre> doSomething(MutableList&lt;String&gt;) or doSomething(MutableList&lt;Int&gt;) fun doSomething(list: MutableList&lt;VariableObject&gt;){}</pre></div></object> - MutableList<object> variable in method (Kotlin) 如何在 Kotlin 中交换 MutableList 中的元素? - How to swap elements in MutableList in Kotlin? 获取可变列表<mutablelist<int> &gt; 从列表<list<int> &gt; 在 Kotlin </list<int></mutablelist<int> - Get MutableList<MutableList<Int>> from List<List<Int>> in Kotlin Kotlin - mutableList 总是返回空列表 - Kotlin - mutableList always returns empty list Kotlin - 根据对象属性对 MutableList 进行排序 - Kotlin - Sort MutableList based on Object Property Kotlin List和MutableList:两个不同的引用,指向同一个集合对象 - Kotlin List and MutableList: two different references, pointed to the same collection object Kotlin、Android - 如何转换 MutableLiveData <mutablelist< something> &gt; 到 LiveData <list< something> &gt; </list<></mutablelist<> - Kotlin, Android - How to transform MutableLiveData<MutableList< something >> to LiveData<List< something >>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM