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

org.dstadler.commons.collections.MappedCounterImpl Maven / Gradle / Ivy

There is a newer version: 1.3.4
Show newest version
package org.dstadler.commons.collections;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Default implementation of a {@link MappedCounter}.
 *
 * @param 
 * @author dominik.stadler
 */
public class MappedCounterImpl implements MappedCounter {

	// sort on values, highest value first
	private Map map = new HashMap<>();

	@Override
	public void addInt(T k, int v) {
		if (!map.containsKey(k)) {
			map.put(k, v);
		} else {
			map.put(k, map.get(k) + v);
		}
	}

	@Override
	public int get(T k) {
		return map.containsKey(k) ? map.get(k) : 0;
	}

	@Override
	public int remove(T key) {
		return map.remove(key);
	}

	@Override
	public Set keys() {
		return map.keySet();
	}

	@Override
	public Set> entries() {
		return map.entrySet();
	}

	@Override
	public Map sortedMap() {
		List> list = new LinkedList<>(map.entrySet());
		Collections.sort(list, new Comparator>() {

			@Override
			public int compare(Map.Entry o1, Map.Entry o2) {
				// reverse ordering to get highest values first
				return (-1) * o1.getValue().compareTo(o2.getValue());
			}
		});

		Map result = new LinkedHashMap<>();
		for (Iterator> it = list.iterator(); it.hasNext();) {
			Map.Entry entry = it.next();
			result.put(entry.getKey(), entry.getValue());
		}
		return result;
	}

	@Override
	public int sum() {
		int sum = 0;
		for(Integer i : map.values()) {
			sum += i;
		}
		return sum;
	}

	@Override
	public String toString() {
		return map.toString();
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy