Sync Integ to Master
[sdc.git] / catalog-dao / src / main / java / org / openecomp / sdc / be / dao / utils / MapUtil.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.dao.utils;
22
23 import java.util.*;
24 import java.util.function.Function;
25 import java.util.stream.Collector;
26 import java.util.stream.Collectors;
27
28 import static java.util.stream.Collectors.groupingBy;
29
30 /**
31  * Utility class to ease map manipulation.
32  */
33 public final class MapUtil {
34         private MapUtil() {
35         }
36
37         /**
38          * Try to get a value following a path in the map. For example :
39          * MapUtil.get(map, "a.b.c") correspond to: map.get(a).get(b).get(c)
40          * 
41          * @param map
42          *            the map to search for path
43          * @param path
44          *            keys in the map separated by '.'
45          */
46         public static Object get(Map<String, ? extends Object> map, String path) {
47                 String[] tokens = path.split("\\.");
48                 if (tokens.length == 0) {
49                         return null;
50                 } else {
51                         Object value = map;
52                         for (String token : tokens) {
53                                 if (!(value instanceof Map)) {
54                                         return null;
55                                 } else {
56                                         @SuppressWarnings("unchecked")
57                                         Map<String, Object> nested = (Map<String, Object>) value;
58                                         if (nested.containsKey(token)) {
59                                                 value = nested.get(token);
60                                         } else {
61                                                 return null;
62                                         }
63                                 }
64                         }
65                         return value;
66                 }
67         }
68
69         /**
70          *
71          * @param valuesToMap the list of values to group
72          * @param groupingFunction the function to group the list values by
73          * @return a map of list of values grouped by a key, as specified in the {@code groupingFunction}
74          */
75         public static <K,V> Map<K,List<V>> groupListBy(Collection<V> valuesToMap, Function<V,K> groupingFunction) {
76                 return valuesToMap.stream().collect(Collectors.groupingBy(groupingFunction));
77         }
78
79         /**
80          *
81          * @param valuesToMap list of values to map
82          * @param mappingFunction a function which specifies how to map each element on the list
83          * @return a map created by mapping each element from the {@code valuesToMap} as specified in the {@code mappingFunction}
84          */
85         public static <K,V> Map<K,V> toMap(Collection<V> valuesToMap, Function<V,K> mappingFunction) {
86                 return Optional.ofNullable(valuesToMap).orElse(new ArrayList<>()).stream().collect(Collectors.toMap(mappingFunction, Function.identity()));
87         }
88
89         /**
90          *
91          * @param map the map of which it keys to convert
92          * @param keyMappingFunction a function which converts the key object
93          * @return a map with converted keys.
94          */
95         public static <K,U, V> Map<U, List<V>> convertMapKeys(Map<K, List<V>> map, Function<K,U> keyMappingFunction) {
96                 return map.entrySet().stream()
97                                 .collect(Collectors.toMap(entry -> keyMappingFunction.apply(entry.getKey()),
98                                                                                   Map.Entry::getValue));
99         }
100
101         /**
102          * Create a new hash map and fills it from the given keys and values
103          * (keys[index] -> values[index].
104          * 
105          * @param keys
106          *            The array of keys.
107          * @param values
108          *            The array of values.
109          * @return A map that contains for each key element in the keys array a
110          *         value from the values array at the same index.
111          */
112         public static <K, V> Map<K, V> newHashMap(K[] keys, V[] values) {
113                 Map<K, V> map = new HashMap<K, V>();
114                 if (keys == null || values == null || keys.length != values.length) {
115                         throw new IllegalArgumentException("keys and values must be non-null and have the same size.");
116                 }
117                 for (int i = 0; i < keys.length; i++) {
118                         map.put(keys[i], values[i]);
119                 }
120                 return map;
121         }
122 }