Kotlin-使用startsWith()比较两个列表

时间:2019-06-18 18:52:56

标签: android kotlin

我想要一种遍历keyList的更好方法,如果某个键以比较器中的一个开始,以获取该比较器字符串并将其作为标题添加到Map中,就像MutableMap> ..与比较器匹配的关键项。

keysList: List<String>
val comparators = listOf("error", "customer", "custom", "feature")

到目前为止,我是这样做的

private fun addToMap(key: String, attributeMap: MutableMap<String, MutableList<String>>) {
        val list: MutableList<String> = attributeMap[getHeader(key)] ?: mutableListOf()
        list.add(key)
        attributeMap[getHeader(key)] = list
    }


    private fun getHeader(key: String): String {
        val compareMap = mapOf("error" to "Error Attributes", "customer" to "Customer Attributes",
            "custom" to "Customer Attributes", "feature" to "Feature Attributes", "request.header" to "Request Header Attributes",
            "request.parameter" to "Request Parameter Attributes", "request" to "Other Request Attributes")
        val defaultKeys = listOf("error.expected", "error.class", "error.message", "host", "httpResponseCode", "transactionName", "transactionUiName") // contains

        for ((k, v) in compareMap) {
            return if (key.startsWith(k)) {
                v
            } else if (key in defaultKeys) {
                "Error Attributes"
            } else {
                "Custom Attributes"
            }
        }
        return "Custom Attributes"
    }

1 个答案:

答案 0 :(得分:0)

您可以像这样使用.any函数:

if (comparators.any { key.startsWith(it) })
    // add to map