re base code
[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.BinaryOperator;
25 import java.util.function.Function;
26 import java.util.stream.Collectors;
27 import java.util.stream.Stream;
28
29 import static java.util.stream.Collectors.toList;
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  the map to search for path
42      * @param path keys in the map separated by '.'
43      */
44     public static Object get(Map<String, ? extends Object> map, String path) {
45         String[] tokens = path.split("\\.");
46         if (tokens.length == 0) {
47             return null;
48         } else {
49             Object value = map;
50             for (String token : tokens) {
51                 if (!(value instanceof Map)) {
52                     return null;
53                 } else {
54                     @SuppressWarnings("unchecked")
55                     Map<String, Object> nested = (Map<String, Object>) value;
56                     if (nested.containsKey(token)) {
57                         value = nested.get(token);
58                     } else {
59                         return null;
60                     }
61                 }
62             }
63             return value;
64         }
65     }
66
67     /**
68      * @param valuesToMap      the list of values to group
69      * @param groupingFunction the function to group the list values by
70      * @return a map of list of values grouped by a key, as specified in the {@code groupingFunction}
71      */
72     public static <K, V> Map<K, List<V>> groupListBy(Collection<V> valuesToMap, Function<V, K> groupingFunction) {
73         return valuesToMap.stream().collect(Collectors.groupingBy(groupingFunction));
74     }
75
76     /**
77      * @param valuesToMap     list of values to map
78      * @param mappingFunction a function which specifies how to map each element on the list
79      * @return a map created by mapping each element from the {@code valuesToMap} as specified in the {@code mappingFunction}
80      */
81     public static <K, V> Map<K, V> toMap(Collection<V> valuesToMap, Function<V, K> mappingFunction) {
82         return toMap(valuesToMap, mappingFunction, throwingMerger());
83     }
84     
85     public static <K, V> Map<K, V> toMap(Collection<V> valuesToMap, Function<V, K> mappingFunction, BinaryOperator<V> mergeFunction) {
86         return streamOfNullable(valuesToMap).collect(Collectors.toMap(mappingFunction, Function.identity(), mergeFunction));
87     }
88
89
90     /**
91      * merge two maps. if a key exists in both maps, takes the value from {@code first}
92      *
93      * @param first  the first map to merge
94      * @param second the second map to merge
95      * @return the merged map
96      */
97     public static <K, V> Map<K, V> mergeMaps(Map<K, V> first, Map<K, V> second) {
98         if (first == null && second == null) {
99             return new HashMap<>();
100         }
101         if (first != null && second == null) {
102             return new HashMap<>(first);
103         }
104         if (first == null) {
105             return new HashMap<>(second);
106         }
107         Map<K, V> mergedMap = new HashMap<>(first);
108         second.forEach(mergedMap::putIfAbsent);
109         return mergedMap;
110     }
111
112     public static <K, V> List<V> flattenMapValues(Map<K, List<V>> mapToFlatten) {
113         if (mapToFlatten == null) {
114             return new ArrayList<>();
115         }
116         return mapToFlatten.values().stream().flatMap(Collection::stream).collect(toList());
117     }
118
119     /**
120      * @param map                the map of which it keys to convert
121      * @param keyMappingFunction a function which converts the key object
122      * @return a map with converted keys.
123      */
124     public static <K, U, V> Map<U, List<V>> convertMapKeys(Map<K, List<V>> map, Function<K, U> keyMappingFunction) {
125         return map.entrySet().stream()
126                 .collect(Collectors.toMap(entry -> keyMappingFunction.apply(entry.getKey()),
127                         Map.Entry::getValue));
128     }
129
130     /**
131      * Create a new hash map and fills it from the given keys and values
132      * (keys[index] -> values[index].
133      *
134      * @param keys   The array of keys.
135      * @param values The array of values.
136      * @return A map that contains for each key element in the keys array a
137      * value from the values array at the same index.
138      */
139     public static <K, V> Map<K, V> newHashMap(K[] keys, V[] values) {
140         Map<K, V> map = new HashMap<>();
141         if (keys == null || values == null || keys.length != values.length) {
142             throw new IllegalArgumentException("keys and values must be non-null and have the same size.");
143         }
144         for (int i = 0; i < keys.length; i++) {
145             map.put(keys[i], values[i]);
146         }
147         return map;
148     }
149     
150     
151     /**
152      * Returns a merge function, suitable for use in
153      * {@link Map#merge(Object, Object, BiFunction) Map.merge()} or
154      * {@link #toMap(Function, Function, BinaryOperator) toMap()}, which always
155      * throws {@code IllegalStateException}.  This can be used to enforce the
156      * assumption that the elements being collected are distinct.
157      *
158      * @param <T> the type of input arguments to the merge function
159      * @return a merge function which always throw {@code IllegalStateException}
160      */
161     private static <T> BinaryOperator<T> throwingMerger() {
162         return (u,v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); };
163     }
164
165     public static <V> Stream<V> streamOfNullable(Collection<V> collection) {
166         return collection == null? Stream.empty(): collection.stream();
167     }
168     
169     public static<T> Stream<T> streamOfNullable(T t) {
170         return t == null ? Stream.empty() : Stream.of(t);
171     }
172 }