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

org.d2ab.collection.Maps Maven / Gradle / Ivy

There is a newer version: 2.3.0
Show newest version
/*
 * Copyright 2016 Daniel Skogquist Åborg
 *
 * 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 org.d2ab.collection;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.IntFunction;
import java.util.function.Supplier;

/**
 * Utility methods for {@link Map} instances
 */
public class Maps {
	public static  Entry entry(K key, V value) {
		return new Entry() {
			@Override
			public K getKey() {
				return key;
			}

			@Override
			public V getValue() {
				return value;
			}

			@Override
			public V setValue(V value) {
				throw new UnsupportedOperationException();
			}
		};
	}

	public static  Builder builder(IntFunction> constructor, int initialCapacity) {
		return new Builder<>(() -> constructor.apply(initialCapacity));
	}

	public static  Builder builder(K key, V value) {
		return Maps.builder().put(key, value);
	}

	public static  Builder builder() {
		return builder(HashMap::new);
	}

	public static  Builder builder(Supplier> constructor) {
		return new Builder<>(constructor);
	}

	public static class Builder {
		private Supplier> constructor;
		private Map map;

		private Builder(Supplier> constructor) {
			this.constructor = constructor;
		}

		public Builder put(K key, V value) {
			if (map == null)
				map = constructor.get();
			map.put(key, value);
			return this;
		}

		public Map build() {
			Map result = map;
			map = null;
			return result;
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy