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

at.molindo.utils.collections.CounterMap Maven / Gradle / Ivy

There is a newer version: 3.0.0
Show newest version
/**
 * Copyright 2010 Molindo GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.molindo.utils.collections;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import at.molindo.utils.data.Pair;

public class CounterMap implements Iterable> {

	public static final int UNKNOWN = -1;
	private final Map _counters = new HashMap();

	public CounterMap() {

	}

	public CounterMap(final Collection objects) {

	}

	public CounterMap(final Collection objects, final int start) {
		for (final T o : objects) {
			_counters.put(o, new Counter(start));
		}
	}

	public int getCount(final T obj) {
		final Counter inc = _counters.get(obj);
		return inc != null ? inc.get() : UNKNOWN;
	}

	public int increment(final T obj) {
		final Counter c = _counters.get(obj);
		if (c == null) {
			_counters.put(obj, new Counter(1));
			return 1;
		} else {
			return c.increment();
		}
	}

	public boolean contains(final T obj) {
		return _counters.get(obj) != null;
	}

	public boolean add(final T obj, final int start) {
		if (!_counters.containsKey(obj)) {
			_counters.put(obj, new Counter(start));
			return true;
		} else {
			return false;
		}
	}

	public int remove(final T obj) {
		final Counter inc = _counters.remove(obj);
		return inc == null ? UNKNOWN : inc.get();
	}

	public int size() {
		return _counters.size();
	}

	@Override
	public String toString() {
		return "[CounterMap: " + _counters + "]";
	}

	private static class Counter {
		private int _val;

		protected Counter(final int val) {
			_val = val;
		}

		protected int increment() {
			return ++_val;
		}

		protected int get() {
			return _val;
		}

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

	}

	@Override
	public Iterator> iterator() {
		return new Iterator>() {

			private final Iterator> _iter = _counters.entrySet().iterator();

			@Override
			public boolean hasNext() {
				return _iter.hasNext();
			}

			@Override
			public Pair next() {
				final Map.Entry e = _iter.next();
				return new Pair(e.getKey(), e.getValue().get());
			}

			@Override
			public void remove() {
				throw new UnsupportedOperationException();
			}

		};
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy