I am writing an Android application and I'm using a Java class that uses has a loop as follows:
for (Set<I> itemset : candidateList2) {
    supportCountMap.put(itemset, supportCountMap.getOrDefault(itemset,0)+ 1);
}
I get the warning Call requires API level 24(current min is 16) on the method:
supportCountMap.getOrDefault(itemset,0)+1);
Is there any workaround to this method such that it can work on phones with an SDK version lower than 24 e.g Marshmallow(23) and Lollipop(21)?
Kotlin: Simply use the elvis operator :
  val value = map[key] ?: 0
if map[key] is null then the value will be 0.
I suggest creating MapCompat class, copy Map.getOrDefault implementation and pass your map as an extra argument: 
public class MapCompat {
    public static <K, V> V getOrDefault(@NonNull Map<K, V> map, K key, V defaultValue) {
        V v;
        return (((v = map.get(key)) != null) || map.containsKey(key))
                ? v
                : defaultValue;
    }
}
This pattern is broadly used in Android support libraries, e.g. ContextCompat.getColor is good example 
You can always implement the same logic yourself:
for (Set<I> itemset : candidateList2) {
    Integer value = supportCountMap.get(itemset);
    if (value == null) {
        value = 0;
    }
    supportCountMap.put(itemset, value + 1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With