
package de.ivu.elect.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 */
public class MapBuilder {

  public static <Element, Key> Map<Key, Element> newMapFrom(Collection<Element> elements, Function<Element, Key> f) {
    Map<Key, Element> map = new HashMap<>();
    for (Element element : elements) {
      map.put(f.apply(element), element);
    }
    return map;
  }

  public static <Element, Key> Map<Key, List<Element>> newMapMultipleEntriesFrom(Collection<? extends Element> elements, Function<Element, Key> f) {
    Map<Key, List<Element>> map = new HashMap<>();
    for (Element element : elements) {
      Key key = f.apply(element);
      if (key != null) {
        List<Element> list = map.get(key);
        if (list == null) {
          list = new ArrayList<>();
          map.put(key, list);
        }
        list.add(element);
      }
    }

    return map;
  }

}