首页 > 解决方案 > kotlin 是否有用于从两种不同类型的列表中获取公共数据的高阶函数?

问题描述

我有与此链接中描述的相同的问题(但它很快) 从两种不同类型的数组中获取公共数据

我努力了 :

 val list=ArrayList<Model>()
 val list1=ArrayList<Model1>()
 val hashMap=Hashmap<Int,Int>()
 for (i in list.indices) {
       val data = list1.filter { it.name == list[i].name }
        if (data.isNotEmpty()) {
        hashMap.put(data[0].id,list[i].id)
      }
    }

标签: androidkotlinhigher-order-functions

解决方案


编辑:根据下面的评论,这是一种无需使用谓词迭代两次的方法:

val map = list.mapNotNull{el -> 
        list1.firstOrNull{el1 -> el.name == el1.name}?.let{el1 -> el.id to el1.id}
    }.toMap()

推荐阅读