Kotlin中如何忽略大小写与空格,通过关键词匹配获取Map对应值?
How to Get Values by Keyword (Ignoring Case & Spaces)
Absolutely! Since your versionsList.getValue() method only supports exact matches and doesn’t offer options for case insensitivity or partial matches, you’ll need to implement a custom solution that loops through all entries. This is straightforward—here’s how to make it work:
Core Approach
The idea is to:
- Preprocess both the target keyword and each key in your list (convert to lowercase, remove all spaces) to eliminate case and whitespace differences.
- Loop through every key-value pair, check if the processed key contains your processed keyword.
- Return the matching value(s) once found.
Example Implementation
Assuming your versionsList is a collection you can iterate over (like a JavaScript Map or similar structure), here’s a reusable function:
function getValueByKeyword(versionsList, keyword) { // Clean up the keyword: lowercase, remove all spaces const cleanedKeyword = keyword.toLowerCase().replace(/\s/g, ''); // Loop through every entry in the list for (const [key, value] of versionsList.entries()) { // Clean up the current key the same way const cleanedKey = key.toLowerCase().replace(/\s/g, ''); // Check if the cleaned key includes the cleaned keyword if (cleanedKey.includes(cleanedKeyword)) { return value; // Returns the first matching value } } return null; // Return null or a default value if no match is found } // Usage example var bananaValue = getValueByKeyword(versionsList, "banana");
Notes to Adapt to Your Language
- If you’re using a different language (like Java, C#, etc.), the syntax will change, but the logic stays the same:
- Iterate over all key-value pairs (e.g.,
for (Map.Entry<String, Double> entry : versionsList.entrySet())in Java) - Use language-specific string methods to lowercase and remove spaces (e.g.,
key.toLowerCase().replaceAll("\\s", "")in Java) - Check for substring inclusion (e.g.,
cleanedKey.contains(cleanedKeyword)in Java)
- Iterate over all key-value pairs (e.g.,
- If multiple keys might match your keyword (e.g., both
yellowBananasandgreenBananas), modify the function to collect all matching values into an array/list instead of returning the first one.
内容的提问来源于stack exchange,提问作者ConnectionistSystems
相关产品推荐
相关产品推荐

