Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to getOrDefault for devices below API 24 Android

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)?

like image 925
ic90 Avatar asked Dec 18 '16 19:12

ic90


3 Answers

Kotlin: Simply use the elvis operator :

  val value = map[key] ?: 0

if map[key] is null then the value will be 0.

like image 163
Saurabh Padwekar Avatar answered Nov 09 '22 05:11

Saurabh Padwekar


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

like image 29
Krzysztof Skrzynecki Avatar answered Nov 09 '22 05:11

Krzysztof Skrzynecki


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);
}
like image 4
Mureinik Avatar answered Nov 09 '22 05:11

Mureinik