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

org.jspringbot.keyword.map.MapSetHelper Maven / Gradle / Ivy

There is a newer version: 1.9
Show newest version
package org.jspringbot.keyword.map;

import org.apache.commons.lang.StringUtils;
import org.jspringbot.JSpringBotLogger;

import java.util.*;


public class MapSetHelper {

    private static final JSpringBotLogger LOGGER = JSpringBotLogger.getLogger(MapSetHelper.class);

    private Map> items;

    public MapSetHelper() {
        this.items = new LinkedHashMap>();
    }

    public void reset() {
        items.clear();
    }

    public boolean add(String key, String value) {
        Set values = items.get(key);

        if(values == null) {
            values = new LinkedHashSet();
            items.put(key, values);
        }

        return values.add(value);
    }

    public String randomConcat(String key, String delimiter, int size) {
        if(!items.containsKey(key)) {
            throw new IllegalArgumentException("No values for key " + key);
        }

        Set values = items.get(key);

        if(size > values.size()) {
            LOGGER.info("size reduced to actual item size: from " + size + " to " + values.size());
            size = values.size();
        }

        List shuffled = new ArrayList(values);

        Collections.shuffle(shuffled);

        return StringUtils.join(shuffled.subList(0, size), delimiter);
    }

    public Set getKeys() {
        if(items.isEmpty()) {
            throw new IllegalArgumentException("Map is empty");
        }

        return items.keySet();

    }

    public String getRandomKey() {
        if(items.isEmpty()) {
            throw new IllegalArgumentException("Map is empty");
        }

        List shuffled = new ArrayList(items.keySet());
        Collections.shuffle(shuffled);

        return shuffled.iterator().next();
    }

    public int size(String key) {
        if(!items.containsKey(key)) {
            throw new IllegalArgumentException("No values for key " + key);
        }

        return items.get(key).size();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy