Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//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 {
    /**
     *
     * @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;
    }
}