All Downloads are FREE. Search and download functionalities are using the official Maven repository.

zone.cogni.libs.core.utils.MapUtils Maven / Gradle / Ivy

package zone.cogni.libs.core.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public abstract class MapUtils {

  public static  Map addOrRemove(Map map, T key, U value) {
    if (value == null) map.remove(key);
    else map.put(key, value);
    return map;
  }

  public static  void copyMap(Map> map, Map> copy) {
    map.entrySet().forEach(entry -> copy.put(entry.getKey(), new HashSet<>(entry.getValue())));
  }

  public static  boolean addValueToMappedSet(Map> map, T key, U value) {
    Set set = map.get(key);
    if (set == null) {
      map.put(key, set = new HashSet<>());
    }
    return set.add(value);
  }

  public static  boolean addValuesToMappedSet(Map> map, T key, Collection values) {
    Set set = map.get(key);
    if (set == null) {
      map.put(key, set = new HashSet<>());
    }
    return set.addAll(values);
  }

  public static  boolean addValueToMappedList(Map> map, T key, U value) {
    List set = map.get(key);
    if (set == null) {
      map.put(key, set = new ArrayList());
    }
    return set.add(value);
  }

  public static  boolean addValuesToMappedList(Map> map, T key, Collection values) {
    List set = map.get(key);
    if (set == null) {
      map.put(key, set = new ArrayList());
    }
    return set.addAll(values);
  }

  public static  U addEntryToMappedMap(Map> map, T key, K entryKey, U entryValue) {
    Map set = map.get(key);
    if (set == null) {
      map.put(key, set = new HashMap());
    }
    return set.put(entryKey, entryValue);
  }
}