Alternative to getOrDefault for devices below API 24 Android

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);
}

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