【问题标题】:What's the best way to find an object from a string in kotlin?从 kotlin 中的字符串中查找对象的最佳方法是什么?
【发布时间】:2019-04-06 23:03:56
【问题描述】:

我有一个正在读取成分列表的应用。至此,我已经检索了 2500 种最常见成分的列表。所以我有一个列表,比如 10 种成分作为字符串,以及 2500 种成分的列表,包括名称和其他属性。如果此字符串列表中的成分与成分列表中的成分名称匹配,我想将其添加到另一个列表第三列表中,即存在的成分。我知道如何做到这一点的唯一方法基本上是使用 for 循环。

我会这样做

fun compareLists(listOfIng: List<String>): List<ListIngredientsQuery.Item> {
    var returnList = mutableListOf<ListIngredientsQuery.Item>()
    for (ing in listOfIng) {
        for (serverIngredient in MyApp.metaIngredientList!!) {
            if (serverIngredient.name() == ing) {
                returnList!!.add(serverIngredient)
            }
        }
    }
    return returnList
}

这在技术上可行,但我不得不想象有一种更好、更快的方法,而不是迭代 2500 多个项目,其次数与成分列表中的成分一样多。真正的开发人员喜欢什么样的,合适的,这样做的方式。

【问题讨论】:

    标签: list kotlin


    【解决方案1】:

    由于每种成分的名称都是唯一的,您可以使用哈希映射来存储您的 2500 种成分,并以它的名称作为键。这样你就不需要再遍历那个庞大的集合了,只需按名称查找并让哈希映射处理它。

    【讨论】:

      【解决方案2】:

      要为 Marcin 所说的添加一些代码,我会这样做:

      fun compareLists(listOfIng: List<String>) =
        MyApp.metaIngredientList!!
            .associateBy { it.name() }
            .let { metaIngredientMap -> listOfIng.mapNotNull { metaIngredientMap[it] }}
      

      或者如果我们想避免使用 !!

      fun compareLists(listOfIng: List<String) =
        MyApp.metaIngredientList
            ?.associateBy { it.name() }
            ?.let { metaIngredientMap -> listOfIng.mapNotNull { metaIngredientMap[it] }}
            ?: emptyList<ListIngredientQuery.Item>()
      

      当然,理想情况下,您希望 MyApp.metaIngredientList 已经是一个 Map,而不是为每个操作将其转换为 Map

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-27
        • 1970-01-01
        • 2016-04-30
        • 2011-05-31
        • 1970-01-01
        • 1970-01-01
        • 2014-06-23
        • 1970-01-01
        相关资源
        最近更新 更多