Java Utililty Methods Map Invert

List of utility methods to do Map Invert

Description

The list of methods to do Map Invert are organized into topic(s).

Method

Mapinverse(Map m, Map newMap)
inverse
for (Entry<K, V> entry : m.entrySet()) {
    newMap.put(entry.getValue(), entry.getKey());
return newMap;
Mapinverse(Map map)
inverse
Map<V, K> inverse = new HashMap<>(map.size());
for (Entry<K, V> entry : map.entrySet()) {
    if (inverse.put(entry.getValue(), entry.getKey()) != null) {
        throw new IllegalArgumentException(map + " is not a bijection.");
return inverse;
Mapinverse(Map map)
Generates a map with the original map's values as keys and its keys as values.
Map<V, K> newMap = new HashMap<>(map.size());
for (Map.Entry<K, V> entry : map.entrySet()) {
    if (newMap.containsKey(entry.getValue())) {
        throw new IllegalArgumentException(
                String.format("There are two keys with the value %s in the map", entry.getValue()));
    newMap.put(entry.getValue(), entry.getKey());
return newMap;
CollectioninverseGet(Map map, Object value)
inverse Get
Collection<K> result = new LinkedList<K>();
for (Iterator<Entry<K, V>> it = map.entrySet().iterator(); it.hasNext();) {
    Entry<K, V> name = it.next();
    if (equalsNullOK(value, name.getValue())) {
        result.add(name.getKey());
return result;
...
Mapinvert(Map map)
Inverts the values of a list.
Map<B, A> map1 = new HashMap<>();
map.forEach((k, v) -> map1.put(v, k));
return map1;
HashMapinvert(Map in)
invert
HashMap<V, K> result = new HashMap<V, K>();
for (Map.Entry<K, V> e : in.entrySet()) {
    result.put(e.getValue(), e.getKey());
return result;
Mapinvert(Map map)
Method to invert a map i.e keys becomes values and vice versa
if (map != null) {
    Map<V, K> returnValue = new HashMap<>();
    for (Entry<K, V> entry : map.entrySet()) {
        if (entry != null) {
            returnValue.put(entry.getValue(), entry.getKey());
    return returnValue;
...
List>invert(Map map, String prefix)
invert
List<Map<String, Object>> list = new ArrayList<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
    if (entry.getKey().startsWith(prefix)) {
        String key = entry.getKey().substring(prefix.length());
        if (Iterable.class.isAssignableFrom(entry.getValue().getClass())) {
            int i = 0;
            for (Object e : ((Iterable) entry.getValue())) {
                for (int j = list.size(); j <= i; j++) {
...
Mapinvert(Map map)
invert
Map<U, T> inversion = new HashMap<U, T>();
for (Entry<T, U> e : map.entrySet()) {
    if (inversion.put(e.getValue(), e.getKey()) != null) {
        throw new IllegalArgumentException("Inversion is not a valid map");
return unmodifiableMap(inversion);
MapinvertedMapFrom(Map source)
Returns a map based on the source but with the key & values swapped.
Map<V, K> map = new HashMap<>(source.size());
for (Map.Entry<K, V> entry : source.entrySet()) {
    map.put(entry.getValue(), entry.getKey());
return map;