2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.be.dao.utils;
24 import java.util.function.BinaryOperator;
25 import java.util.function.Function;
26 import java.util.stream.Collectors;
27 import java.util.stream.Stream;
29 import static java.util.stream.Collectors.toList;
31 * Utility class to ease map manipulation.
33 public final class MapUtil {
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)
41 * @param map the map to search for path
42 * @param path keys in the map separated by '.'
44 public static Object get(Map<String, ? extends Object> map, String path) {
45 String[] tokens = path.split("\\.");
46 if (tokens.length == 0) {
50 for (String token : tokens) {
51 if (!(value instanceof Map)) {
54 @SuppressWarnings("unchecked")
55 Map<String, Object> nested = (Map<String, Object>) value;
56 if (nested.containsKey(token)) {
57 value = nested.get(token);
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}
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));
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}
81 public static <K, V> Map<K, V> toMap(Collection<V> valuesToMap, Function<V, K> mappingFunction) {
82 return toMap(valuesToMap, mappingFunction, throwingMerger());
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));
91 * merge two maps. if a key exists in both maps, takes the value from {@code first}
93 * @param first the first map to merge
94 * @param second the second map to merge
95 * @return the merged map
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<>();
101 if (first != null && second == null) {
102 return new HashMap<>(first);
105 return new HashMap<>(second);
107 Map<K, V> mergedMap = new HashMap<>(first);
108 second.forEach(mergedMap::putIfAbsent);
112 public static <K, V> List<V> flattenMapValues(Map<K, List<V>> mapToFlatten) {
113 if (mapToFlatten == null) {
114 return new ArrayList<>();
116 return mapToFlatten.values().stream().flatMap(Collection::stream).collect(toList());
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.
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));
131 * Create a new hash map and fills it from the given keys and values
132 * (keys[index] -> values[index].
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.
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.");
144 for (int i = 0; i < keys.length; i++) {
145 map.put(keys[i], values[i]);
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.
158 * @param <T> the type of input arguments to the merge function
159 * @return a merge function which always throw {@code IllegalStateException}
161 private static <T> BinaryOperator<T> throwingMerger() {
162 return (u,v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); };
165 public static <V> Stream<V> streamOfNullable(Collection<V> collection) {
166 return collection == null? Stream.empty(): collection.stream();
169 public static<T> Stream<T> streamOfNullable(T t) {
170 return t == null ? Stream.empty() : Stream.of(t);