MutableList到Kotlin中的HashMap

时间:2020-05-16 13:29:30

标签: list kotlin hashmap

我想将MutableList的值转换为HashMap。你能帮我吗?这是我的代码:

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))
}

2 个答案:

答案 0 :(得分:0)

使用此解决:

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

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

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

答案 1 :(得分:0)

您可以使用import FirebaseMessaging 将列表转换成List.map()的列表,然后在该列表上使用Pair

toMap()