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

com.github.linushp.commons.MultiListMap Maven / Gradle / Ivy

package com.github.linushp.commons;

import com.github.linushp.commons.ifs.Getter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;

public class MultiListMap {

    private Map> map;

    public MultiListMap() {
        this.map = new HashMap<>();
    }

    public MultiListMap(Map map) {
        this.map = map;
    }

    public synchronized void putElement(S key, T object) {
        List list = getListNotNull(key);
        list.add(object);
    }

    public synchronized void putElements(Getter keyGetter, List objectList) {
        for (T obj : objectList) {
            S key = keyGetter.doGet(obj);
            putElement(key, obj);
        }
    }


    public synchronized void putElementsList(Map> sourceMap) {
        Set>> entrySet = sourceMap.entrySet();
        for (Map.Entry> entry : entrySet) {
            S key = entry.getKey();
            List tList = entry.getValue();
            if (!CollectionUtils.isEmpty(tList)) {
                List list = getListNotNull(key);
                for (T t : tList) {
                    list.add(t);
                }
            }
        }
    }

    public synchronized void putElementsArray(Map sourceMap) {
        Set> entrySet = sourceMap.entrySet();
        for (Map.Entry entry : entrySet) {
            S key = entry.getKey();
            T[] tList = entry.getValue();
            if (!CollectionUtils.isEmpty(tList)) {
                List list = getListNotNull(key);
                for (int i = 0; i < tList.length; i++) {
                    list.add(tList[i]);
                }
            }
        }
    }


    public Map toHashMap() {
        Map result = new HashMap<>();
        Set>> entrySet = map.entrySet();
        for (Map.Entry> entry : entrySet) {
            S key = entry.getKey();
            List tList = entry.getValue();
            if (!CollectionUtils.isEmpty(tList)) {
                result.put(key, tList.get(0));
            }
        }
        return result;
    }

    public List getList(S key) {
        return map.get(key);
    }

    public Map> getMap() {
        return map;
    }

    public synchronized List getListNotNull(S key) {
        List list = map.get(key);
        if (list == null) {
            list = new CopyOnWriteArrayList<>();
            map.put(key, list);
        }
        return list;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy