You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Preprocess both the target keyword and each key in your list (convert to lowercase, remove all spaces) to eliminate case and whitespace differences.
  2. Loop through every key-value pair, check if the processed key contains your processed keyword.
  3. 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)
  • If multiple keys might match your keyword (e.g., both yellowBananas and greenBananas), modify the function to collect all matching values into an array/list instead of returning the first one.

内容的提问来源于stack exchange,提问作者ConnectionistSystems

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:05:31