Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin map add value if doesn't equal

Tags:

android

kotlin

I have a val valuesMap = mutableMapOf<String, String>() I want to add new value if keys of map doesn't equalsIgnoreCase new value.

if(!valuesMap.keys.equalsIgnoreKeys("value")) {
 valuesMap.put("value", null)
}

Something like this, but in kotlin we have only equals method for keys.

like image 739
T. Roman Avatar asked Jun 21 '26 04:06

T. Roman


2 Answers

This iterates through the key set and compares lower-cased keys to the given term (new key).

val map: MutableMap<String, String?> = mutableMapOf()
val term = "value"
val contains = map.keys.any { key ->
    key.toLowerCase() == term.toLowerCase()
}
if (!contains) {
    map.put(term, null)
}
like image 79
Edgars Avatar answered Jun 25 '26 12:06

Edgars


Why not use a specific map for your use case:

val caseInsensitive = TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER)

The following constructor is used here:

public TreeMap(Comparator comparator)

Constructs a new, empty tree map, ordered according to the given comparator. All keys inserted into the map must be mutually comparable by the given comparator: comparator.compare(k1, k2) must not throw a ClassCastException for any keys k1 and k2 in the map. If the user attempts to put a key into the map that violates this constraint, the put(Object key, Object value) call will throw a ClassCastException.

Parameters: comparator - the comparator that will be used to order this map. If null, the natural ordering of the keys will be used.

like image 23
s1m0nw1 Avatar answered Jun 25 '26 14:06

s1m0nw1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!