com.link_intersystems.util.Maps Maven / Gradle / Ivy
Show all versions of lis-commons-util Show documentation
/**
* Copyright 2011 Link Intersystems GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.link_intersystems.util;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
* The {@link Maps} class provides {@link Map} related utility methods.
*
* @author - René Link {@literal }
* @since 1.3.0;
*/
public abstract class Maps {
private static final double HASH_MAP_LOAD_FACTOR = 1 / 0.75;
/**
* Safely builds a map from a {@link Collection} or objects by preventing duplicate keys.
* The object keys are calculated via a {@link ParameterizedObjectFactory}. The
* {@link ParameterizedObjectFactory} must ensure that a distinct key for
* every object instance in the collection is generated. If there are two
* instances that have the same key a {@link KeyCollisionException} is thrown.
*
* @param the key's type
* @param the value's type
* @param objects the {@link Collection} of objects the key map should be
* generated of.
* @param keyGenFunction the {@link ParameterizedObjectFactory} to use for creating the
* keys.
* @return a map that maps the keys generated by the
* {@link ParameterizedObjectFactory} to the objects of the original
* collection.
* @throws KeyCollisionException if the collection contains two objects that are equal in
* their key which is generated by the
* {@link ParameterizedObjectFactory}.
* @since 1.3.0;
*/
public static Map keyMap(
Collection objects,
Function keyGenFunction)
throws KeyCollisionException {
Map map = new HashMap<>(
(int) (objects.size() * HASH_MAP_LOAD_FACTOR));
for (V v : objects) {
K k = keyGenFunction.apply(v);
if (map.containsKey(k)) {
throw new KeyCollisionException(k);
} else {
map.put(k, v);
}
}
return map;
}
}