简体   繁体   English

ArrayList 的转换方法<hashmap<k,v> &gt; 列出<v>在科特林? </v></hashmap<k,v>

[英]How to convert ArrayList<HashMap<K,V>> to List<V> in kotlin?

I would like to convert an ArrayList of HashMap into a List of the maps values .我想将HashMapArrayList转换为地图values List

The values within the map are of a custom class MapValuesClass .地图中的values属于自定义类MapValuesClass The key is not important and I can lose it. key不重要,我可以把它弄丢。

The attempt1 recommended below loses the groupings of the map entries.下面推荐的attempt1丢失了映射条目的分组。 How can I do something similar to flatmap but have each item in the list of type MapValuesClass ?我怎样才能做类似于flatmap的事情,但每个项目都在MapValuesClass类型的列表中? See desired result below.请参阅下面的预期结果。

Attempt 1尝试 1

val attempt1 = arrayListOfHashmaps.flatMap { it.values }

在此处输入图像描述

Desired Result期望的结果

在此处输入图像描述

    @Test
    fun test() {
        val arrayListOfHashmaps = arrayListOf(
            hashMapOf(
                "string" to "value1",
                "Int" to 1,
                "Double" to 1.0
            ),
            hashMapOf(
                "string" to "value2",
                "Int" to 2,
                "Double" to 2.0
            ),
            hashMapOf(
                "string" to "value3",
                "Int" to 3,
                "Double" to 3.0
            ),
        )

        val attempt1 = arrayListOfHashmaps.flatMap { it.values }
        
        val desired = listOf(
            MapValuesClass("value1", 1, 1.0),
            MapValuesClass("value2", 2, 2.0),
            MapValuesClass("value3", 3, 3.0),
        )
    }


    data class MapValuesClass(
        val string: String,
        val integer: Int,
        val double: Double,
    )


You can convert the list with map as below:您可以使用地图转换列表,如下所示:

val desired = arrayListOfHashmaps.map{ MapValuesClass(it["string"] as String,
                it["Int"] as Int,
                it["Double"] as Double)}

But if needed, you have to do some exception handling based on your data to avoid any conversion error但是如果需要,你必须根据你的数据做一些异常处理以避免任何转换错误

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

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