Java Collection Reverse reverseMap(Map> input)

Here you can find the source of reverseMap(Map> input)

Description

reverse Map

License

Open Source License

Parameter

Parameter Description
input map to reverse
T type of map and collection

Return

reversed map with value sets switched with key sets.

Declaration

public static <T> Map<T, HashSet<T>> reverseMap(Map<T, ? extends Collection<T>> input) 

Method Source Code


//package com.java2s;
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

import java.util.*;

public class Main {
    /**/*  w ww . j a va2s. c om*/
     *
     * @param input map to reverse
     * @param <T> type of map and collection
     * @return reversed map with value sets switched with key sets.
     */
    public static <T> Map<T, HashSet<T>> reverseMap(Map<T, ? extends Collection<T>> input) {

        Map<T, HashSet<T>> ret = new HashMap<T, HashSet<T>>();

        for (Map.Entry<T, ? extends Collection<T>> entry : input.entrySet()) {

            final Collection<T> values = entry.getValue();
            final T key = entry.getKey();

            //foreach value in key->values mapping
            for (T value : values) {

                //get the reversed collection created when previously iterated keys
                // were associated with this value, value -> keys
                HashSet<T> newValues = ret.get(value);

                //if we've never processed a key that pointed to this value -
                // it's time to initialize the reversed collection from this value to keys that pointed to it
                if (newValues == null) {

                    newValues = new HashSet<T>();
                    ret.put(value, newValues);
                }

                //and obviously put the key in the reversed collection
                newValues.add(key);
            }
        }

        return ret;
    }
}

Related

  1. reverse(Collection collection)
  2. reverse(Collection c)
  3. reverse(Collection input)
  4. reverseOrder(Collection objects)