https://kotlinlang.org logo
#getting-started
Title
# getting-started
c

Chih Wei Lin

03/05/2022, 5:10 PM
How to solve the following problem more elegantly: Given a keyword list and a input data list. Iterate through input data list and if the item contains one of the keywords, put it together. (Sample data and my brute force way are in the thread)
Copy code
val targetKeywords = listOf("red", "blue", "yellow", "white", "black")
val inputData = listOf(
    "one blue",
    "two gray",
    "three black",
    "four blue",
    "blue",
    "five yellow",
    "six gray",
    "yellow",
    "seven black",
    "nine gray",
    "ten blue",
    "purple"
)

val resultMap = targetKeywords.associateWith { mutableListOf<String>() }
inputData.forEach { item ->
    targetKeywords.forEach { color ->
        if (item.contains(color)) {
            resultMap[color]!! += item
            return@forEach
        }
    }
}

print(resultMap)
// result: {red=[], blue=[one blue, four blue, blue, ten blue], yellow=[five yellow, yellow], white=[], black=[three black, seven black]}
v

Vampire

03/05/2022, 9:09 PM
Copy code
val resultMap = targetKeywords.associateWith { color ->
    inputData.filter { item -> color in item }
}
?
🦜 1
👌 2
c

Chih Wei Lin

03/06/2022, 5:15 AM
Cool. TIL the 'in' keyword
r

Roukanken

03/07/2022, 10:38 AM
note that it's not exactly the most efficient solution so if your data can get large you want to consider alternatives
v

Vampire

03/07/2022, 11:51 AM
They asked for elegant way, not fast way. 😁
👍 1
4 Views