Saturday, December 24, 2016

An useful util to handle nested collection in Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
 
public class CommonUtil {
 
    public static <K, V, O extends V> V getAndCreateIfNotExist(K key, Map<K, V> map, Class<O> c) {
        V result = map.get(key);
        if (result == null) {
            synchronized (map) {
                result = map.get(key);
                if (result == null) {
                    try {
                        result = c.newInstance();
                    } catch (Exception e) {
                        throw new RuntimeException("Error in getAndCreateIfNotExist", e);
                    }
 
                    map.put(key, result);
                }
            }
        }
        return result;
    }
    // Test
    public static void main(String[] args) {
        Map<String, Set<String>> phoneNumbersPerName = new HashMap<>();
        String personName = "Alex";
        Set<String> phoneNumbers = getAndCreateIfNotExist(personName, phoneNumbersPerName, HashSet.class);
        phoneNumbers.add("01234567891");
        phoneNumbers.add("09090909090");
        System.out.println(phoneNumbersPerName);
        // {Alex=[09090909090, 01234567891]}
    }
}

No comments :

Post a Comment