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

de.invation.code.toval.misc.MapUtils Maven / Gradle / Ivy

Go to download

TOVAL comprises a set of java classes for common programming issues. It includes utils for arrays, lists, sets and collections for convenient handling and modification, but also support for mathematic definitions concerning logic (clauses + resolution) together with some algorithms for permutations, powersets and resolution. Additionally it contains a number of types for multisets, matrices with object keys and much more.

The newest version!
package de.invation.code.toval.misc;

import de.invation.code.toval.types.HashList;
import java.util.List;
import java.util.Map;

public class MapUtils {

	/**
	 * String for value separation.
* Used for generating String representations of collections. */ public static final char VALUE_MAPPING = '='; /** * String for value separation.
* Used for generating String representations of collections. */ public static final char VALUE_SEPARATION = ' '; /** * Default precision used for String representations of map elements having * type Float or Double. */ public static final int DEFAULT_PRECISION = 2; /** * String representation for empty maps. */ public static final String EMPTY_MAP = "[]"; public static String toString(Map map) { return toString(map, DEFAULT_PRECISION, DEFAULT_PRECISION); } public static String toString(Map map, int precision) { return toString(map, precision, precision); } public static String toString(Map map, int keyPrecision, int valuePrecision) { if (map == null) throw new NullPointerException(); if (map.isEmpty()) return EMPTY_MAP; List v = new HashList<>(); v.addAll(map.keySet()); v.addAll(map.values()); return String.format(getFormat(map, keyPrecision, valuePrecision), v.toArray()); } /** * Returns a format-String that can be used to generate a String * representation of a map using the String.format method. * * @param map * Map for which a String representation is desired * @param keyPrecision * Desired precision for Float and * Double elements * @param valuePrecision * Desired precision for Float and * Double elements * @return Format-String for map * @see String#format(String, Object...) */ private static String getFormat(Map map, int keyPrecision, int valuePrecision) { StringBuilder builder = new StringBuilder(); builder.append('{'); int mappings = map.keySet().size(); int c = 0; for (Object key : map.keySet()) { c++; builder.append(FormatUtils.getIndexedFormat(c, FormatUtils.getFormat(key, keyPrecision))); builder.append(VALUE_MAPPING); builder.append( FormatUtils.getIndexedFormat(mappings + c, FormatUtils.getFormat(map.get(key), valuePrecision))); if (c < mappings) builder.append(VALUE_SEPARATION); } builder.append('}'); return builder.toString(); } }