/*************************************************************************
* *
* CESeCore: CE Security Core *
* *
* This software is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or any later version. *
* *
* See terms of license at gnu.org. *
* *
*************************************************************************/
package org.cesecore.util;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* Utility functions to work with maps.
*
* @version $Id: MapTools.java 28328 2018-02-20 11:46:09Z samuellb $
*/
public final class MapTools {
/** Utility class, cannot be instantiated */
private MapTools() { }
/**
* Adds an item to a map, and returns it. Useful for initialization:
*
* doWorkWithMapExample(addToMap(new HashMap
*
*
Unlike the Unlike the new HashMap<>() {{ put(x,y); }}
pattern, this does not create a new class (which can create problems with de-serialization)
*
* @param map Map to use.
* @param key1 First key.
* @param value1 Value of first key.
* @return Returns the map.
* @see #addToMap(Map, Object, Object, Object, Object)
* @see #addToMap(Map, Object, Object, Object, Object, Object, Object)
*/
public static
* doWorkWithMapExample(unmodifiableMap(0, "none"));
*
*
* new HashMap<>() {{ put(x,y); }}
pattern, this does not create a new class (which can create problems with de-serialization)
*
* @param key1 First key.
* @param value1 Value of first key.
* @return Returns the map.
* @see #unmodifiableMap(Object, Object, Object, Object)
* @see #unmodifiableMap(Object, Object, Object, Object, Object, Object)
*/
public static {'key 1': 'value 1', 'key 2': null}
*/
public static String toString(final Map, ?> map) {
final StringBuilder sb = new StringBuilder();
boolean first = true;
sb.append('{');
for (final Entry,?> entry : map.entrySet()) {
if (!first) sb.append(", ");
appendToStringOrNull(sb, entry.getKey());
sb.append(": ");
appendToStringOrNull(sb, entry.getValue());
}
sb.append('}');
return sb.toString();
}
private static void appendToStringOrNull(final StringBuilder sb, final Object obj) {
if (obj == null) {
sb.append("null");
} else {
sb.append('\'');
sb.append(obj);
sb.append('\'');
}
}
}