|
What this is
Other links
The source code/* * Copyright 2001-2004 The Apache Software Foundation * * 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.apache.commons.collections; import java.io.PrintStream; import java.text.NumberFormat; import java.text.ParseException; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.ResourceBundle; import java.util.SortedMap; import java.util.TreeMap; import org.apache.commons.collections.map.FixedSizeMap; import org.apache.commons.collections.map.FixedSizeSortedMap; import org.apache.commons.collections.map.LazyMap; import org.apache.commons.collections.map.LazySortedMap; import org.apache.commons.collections.map.ListOrderedMap; import org.apache.commons.collections.map.PredicatedMap; import org.apache.commons.collections.map.PredicatedSortedMap; import org.apache.commons.collections.map.TransformedMap; import org.apache.commons.collections.map.TransformedSortedMap; import org.apache.commons.collections.map.TypedMap; import org.apache.commons.collections.map.TypedSortedMap; import org.apache.commons.collections.map.UnmodifiableMap; import org.apache.commons.collections.map.UnmodifiableSortedMap; /** * Provides utility methods and decorators for * {@link Map} and {@link SortedMap} instances. *
MapUtils should not normally be instantiated.
*/
public MapUtils() {
}
// Type safe getters
//-------------------------------------------------------------------------
/**
* Gets from a Map in a null-safe manner.
*
* @param map the map to use
* @param key the key to look up
* @return the value in the Map, null if null map input
*/
public static Object getObject(final Map map, final Object key) {
if (map != null) {
return map.get(key);
}
return null;
}
/**
* Gets a String from a Map in a null-safe manner.
*
* The String is obtained via
* If the value is a
* If the value is a
* The Byte is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @return the value in the Map as a Byte,
* The Short is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @return the value in the Map as a Short,
* The Integer is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @return the value in the Map as a Integer,
* The Long is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @return the value in the Map as a Long,
* The Float is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @return the value in the Map as a Float,
* The Double is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @return the value in the Map as a Double,
* If the value returned from the specified map is not a Map then
*
* If the value is a
* The byte is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @return the value in the Map as a byte,
* The short is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @return the value in the Map as a short,
* The int is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @return the value in the Map as an int,
* The long is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @return the value in the Map as a long,
* The float is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @return the value in the Map as a float,
* The double is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @return the value in the Map as a double,
* If the value is a
* The byte is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @param defaultValue return if the value is null or if the
* conversion fails
* @return the value in the Map as a byte,
* The short is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @param defaultValue return if the value is null or if the
* conversion fails
* @return the value in the Map as a short,
* The int is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @param defaultValue return if the value is null or if the
* conversion fails
* @return the value in the Map as an int,
* The long is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @param defaultValue return if the value is null or if the
* conversion fails
* @return the value in the Map as a long,
* The float is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @param defaultValue return if the value is null or if the
* conversion fails
* @return the value in the Map as a float,
* The double is obtained from the results of {@link #getNumber(Map,Object)}.
*
* @param map the map to use
* @param key the key to look up
* @param defaultValue return if the value is null or if the
* conversion fails
* @return the value in the Map as a double, * This method prints a nicely formatted String describing the Map. * Each map entry will be printed with key and value. * When the value is a Map, recursive behaviour occurs. *
* This method is NOT thread-safe in any special way. You must manually
* synchronize on either this class or the stream as required.
*
* @param out the stream to print to, must not be null
* @param label The label to be used, may be * This method prints a nicely formatted String describing the Map. * Each map entry will be printed with key, value and value classname. * When the value is a Map, recursive behaviour occurs. *
* This method is NOT thread-safe in any special way. You must manually
* synchronize on either this class or the stream as required.
*
* @param out the stream to print to, must not be null
* @param label The label to be used, may be
* This method exists as Jakarta Collections does not depend on logging.
*
* @param ex the exception to log
*/
protected static void logInfo(final Exception ex) {
System.out.println("INFO: Exception: " + ex);
}
/**
* Implementation providing functionality for {@link #debugPrint} and for
* {@link #verbosePrint}. This prints the given map with nice line breaks.
* If the debug flag is true, it additionally prints the type of the object
* value. If the contents of a map include the map itself, then the text
* (this Map) is printed out. If the contents include a
* parent container of the map, the the text (ancestor[i] Map) is
* printed, where i actually indicates the number of levels which must be
* traversed in the sequential list of ancestors (e.g. father, grandfather,
* great-grandfather, etc).
*
* @param out the stream to print to
* @param label the label to be used, may be * This operation assumes that the inverse mapping is well defined. * If the input map had multiple entries with the same value mapped to * different keys, the returned map will map one of those keys to the * value, but the exact key which will be mapped is undefined. * * @see DoubleOrderedMap * @param map the map to invert, may not be null * @return a new HashMap containing the inverted data * @throws NullPointerException if the map is null */ public static Map invertMap(Map map) { Map out = new HashMap(map.size()); for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); out.put(entry.getValue(), entry.getKey()); } return out; } /** * Nice method for adding data to a map in such a way * as to not get NPE's. The point being that if the * value is null, map.put() will throw an exception. * That blows in the case of this class cause you may want to * essentially treat put("Not Null", null ) == put("Not Null", "") * We will still throw a NPE if the key is null cause that should * never happen. * * @param map the map to add to, may not be null * @param key the key * @param value the value * @throws NullPointerException if the map is null */ public static void safeAddToMap(Map map, Object key, Object value) throws NullPointerException { if (value == null) { map.put ( key, "" ); } else { map.put ( key, value ); } } // Map decorators //----------------------------------------------------------------------- /** * Returns a synchronized map backed by the given map. * * You must manually synchronize on the returned buffer's iterator to * avoid non-deterministic behavior: * * * Map m = MapUtils.synchronizedMap(myMap); * Set s = m.keySet(); // outside synchronized block * synchronized (m) { // synchronized on MAP! * Iterator i = s.iterator(); * while (i.hasNext()) { * process (i.next()); * } * } ** * This method uses the implementation in {@link java.util.Collections Collections}. * * @param map the map to synchronize, must not be null * @return a synchronized map backed by the given map * @throws IllegalArgumentException if the map is null */ public static Map synchronizedMap(Map map) { return Collections.synchronizedMap(map); } /** * Returns an unmodifiable map backed by the given map. * * This method uses the implementation in the decorators subpackage. * * @param map the map to make unmodifiable, must not be null * @return an unmodifiable map backed by the given map * @throws IllegalArgumentException if the map is null */ public static Map unmodifiableMap(Map map) { return UnmodifiableMap.decorate(map); } /** * Returns a predicated (validating) map backed by the given map. * * Only objects that pass the tests in the given predicates can be added to the map. * Trying to add an invalid object results in an IllegalArgumentException. * Keys must pass the key predicate, values must pass the value predicate. * It is important not to use the original map after invoking this method, * as it is a backdoor for adding invalid objects. * * @param map the map to predicate, must not be null * @param keyPred the predicate for keys, null means no check * @param valuePred the predicate for values, null means no check * @return a predicated map backed by the given map * @throws IllegalArgumentException if the Map is null */ public static Map predicatedMap(Map map, Predicate keyPred, Predicate valuePred) { return PredicatedMap.decorate(map, keyPred, valuePred); } /** * Returns a typed map backed by the given map. * * Only keys and values of the specified types can be added to the map. * * @param map the map to limit to a specific type, must not be null * @param keyType the type of keys which may be added to the map, must not be null * @param valueType the type of values which may be added to the map, must not be null * @return a typed map backed by the specified map * @throws IllegalArgumentException if the Map or Class is null */ public static Map typedMap(Map map, Class keyType, Class valueType) { return TypedMap.decorate(map, keyType, valueType); } /** * Returns a transformed map backed by the given map. * * Each object is passed through the transformers as it is added to the * Map. It is important not to use the original map after invoking this * method, as it is a backdoor for adding untransformed objects. * * @param map the map to transform, must not be null * @param keyTransformer the transformer for the map keys, null means no transformation * @param valueTransformer the transformer for the map values, null means no transformation * @return a transformed map backed by the given map * @throws IllegalArgumentException if the Map is null */ public static Map transformedMap(Map map, Transformer keyTransformer, Transformer valueTransformer) { return TransformedMap.decorate(map, keyTransformer, valueTransformer); } /** * Returns a fixed-sized map backed by the given map. * Elements may not be added or removed from the returned map, but * existing elements can be changed (for instance, via the * {@link Map#put(Object,Object)} method). * * @param map the map whose size to fix, must not be null * @return a fixed-size map backed by that map * @throws IllegalArgumentException if the Map is null */ public static Map fixedSizeMap(Map map) { return FixedSizeMap.decorate(map); } /** * Returns a "lazy" map whose values will be created on demand. * * When the key passed to the returned map's {@link Map#get(Object)} * method is not present in the map, then the factory will be used * to create a new object and that object will become the value * associated with that key. * * For instance: * * Factory factory = new Factory() { * public Object create() { * return new Date(); * } * } * Map lazyMap = MapUtils.lazyMap(new HashMap(), factory); * Object obj = lazyMap.get("test"); ** * After the above code is executed, obj will contain
* a new Date instance. Furthermore, that Date
* instance is the value for the "test" key in the map.
*
* @param map the map to make lazy, must not be null
* @param factory the factory for creating new objects, must not be null
* @return a lazy map backed by the given map
* @throws IllegalArgumentException if the Map or Factory is null
*/
public static Map lazyMap(Map map, Factory factory) {
return LazyMap.decorate(map, factory);
}
/**
* Returns a "lazy" map whose values will be created on demand.
* * When the key passed to the returned map's {@link Map#get(Object)} * method is not present in the map, then the factory will be used * to create a new object and that object will become the value * associated with that key. The factory is a {@link Transformer} * that will be passed the key which it must transform into the value. * * For instance: * * Transformer factory = new Transformer() { * public Object transform(Object mapKey) { * return new File(mapKey); * } * } * Map lazyMap = MapUtils.lazyMap(new HashMap(), factory); * Object obj = lazyMap.get("C:/dev"); ** * After the above code is executed, obj will contain
* a new File instance for the C drive dev directory.
* Furthermore, that File instance is the value for the
* "C:/dev" key in the map.
* * If a lazy map is wrapped by a synchronized map, the result is a simple * synchronized cache. When an object is not is the cache, the cache itself * calls back to the factory Transformer to populate itself, all within the * same synchronized block. * * @param map the map to make lazy, must not be null * @param transformerFactory the factory for creating new objects, must not be null * @return a lazy map backed by the given map * @throws IllegalArgumentException if the Map or Transformer is null */ public static Map lazyMap(Map map, Transformer transformerFactory) { return LazyMap.decorate(map, transformerFactory); } /** * Returns a map that maintains the order of keys that are added * backed by the given map. * * If a key is added twice, the order is determined by the first add. * The order is observed through the keySet, values and entrySet. * * @param map the map to order, must not be null * @return an ordered map backed by the given map * @throws IllegalArgumentException if the Map is null */ public static Map orderedMap(Map map) { return ListOrderedMap.decorate(map); } // SortedMap decorators //----------------------------------------------------------------------- /** * Returns a synchronized sorted map backed by the given sorted map. * * You must manually synchronize on the returned buffer's iterator to * avoid non-deterministic behavior: * * * Map m = MapUtils.synchronizedSortedMap(myMap); * Set s = m.keySet(); // outside synchronized block * synchronized (m) { // synchronized on MAP! * Iterator i = s.iterator(); * while (i.hasNext()) { * process (i.next()); * } * } ** * This method uses the implementation in {@link java.util.Collections Collections}. * * @param map the map to synchronize, must not be null * @return a synchronized map backed by the given map * @throws IllegalArgumentException if the map is null */ public static Map synchronizedSortedMap(SortedMap map) { return Collections.synchronizedSortedMap(map); } /** * Returns an unmodifiable sorted map backed by the given sorted map. * * This method uses the implementation in the decorators subpackage. * * @param map the sorted map to make unmodifiable, must not be null * @return an unmodifiable map backed by the given map * @throws IllegalArgumentException if the map is null */ public static Map unmodifiableSortedMap(SortedMap map) { return UnmodifiableSortedMap.decorate(map); } /** * Returns a predicated (validating) sorted map backed by the given map. * * Only objects that pass the tests in the given predicates can be added to the map. * Trying to add an invalid object results in an IllegalArgumentException. * Keys must pass the key predicate, values must pass the value predicate. * It is important not to use the original map after invoking this method, * as it is a backdoor for adding invalid objects. * * @param map the map to predicate, must not be null * @param keyPred the predicate for keys, null means no check * @param valuePred the predicate for values, null means no check * @return a predicated map backed by the given map * @throws IllegalArgumentException if the SortedMap is null */ public static SortedMap predicatedSortedMap(SortedMap map, Predicate keyPred, Predicate valuePred) { return PredicatedSortedMap.decorate(map, keyPred, valuePred); } /** * Returns a typed sorted map backed by the given map. * * Only keys and values of the specified types can be added to the map. * * @param map the map to limit to a specific type, must not be null * @param keyType the type of keys which may be added to the map, must not be null * @param valueType the type of values which may be added to the map, must not be null * @return a typed map backed by the specified map */ public static SortedMap typedSortedMap(SortedMap map, Class keyType, Class valueType) { return TypedSortedMap.decorate(map, keyType, valueType); } /** * Returns a transformed sorted map backed by the given map. * * Each object is passed through the transformers as it is added to the * Map. It is important not to use the original map after invoking this * method, as it is a backdoor for adding untransformed objects. * * @param map the map to transform, must not be null * @param keyTransformer the transformer for the map keys, null means no transformation * @param valueTransformer the transformer for the map values, null means no transformation * @return a transformed map backed by the given map * @throws IllegalArgumentException if the SortedMap is null */ public static SortedMap transformedSortedMap(SortedMap map, Transformer keyTransformer, Transformer valueTransformer) { return TransformedSortedMap.decorate(map, keyTransformer, valueTransformer); } /** * Returns a fixed-sized sorted map backed by the given sorted map. * Elements may not be added or removed from the returned map, but * existing elements can be changed (for instance, via the * {@link Map#put(Object,Object)} method). * * @param map the map whose size to fix, must not be null * @return a fixed-size map backed by that map * @throws IllegalArgumentException if the SortedMap is null */ public static SortedMap fixedSizeSortedMap(SortedMap map) { return FixedSizeSortedMap.decorate(map); } /** * Returns a "lazy" sorted map whose values will be created on demand. * * When the key passed to the returned map's {@link Map#get(Object)} * method is not present in the map, then the factory will be used * to create a new object and that object will become the value * associated with that key. * * For instance: * * * Factory factory = new Factory() { * public Object create() { * return new Date(); * } * } * SortedMap lazy = MapUtils.lazySortedMap(new TreeMap(), factory); * Object obj = lazy.get("test"); ** * After the above code is executed, obj will contain
* a new Date instance. Furthermore, that Date
* instance is the value for the "test" key.
*
* @param map the map to make lazy, must not be null
* @param factory the factory for creating new objects, must not be null
* @return a lazy map backed by the given map
* @throws IllegalArgumentException if the SortedMap or Factory is null
*/
public static SortedMap lazySortedMap(SortedMap map, Factory factory) {
return LazySortedMap.decorate(map, factory);
}
/**
* Returns a "lazy" sorted map whose values will be created on demand.
* * When the key passed to the returned map's {@link Map#get(Object)} * method is not present in the map, then the factory will be used * to create a new object and that object will become the value * associated with that key. The factory is a {@link Transformer} * that will be passed the key which it must transform into the value. * * For instance: * * Transformer factory = new Transformer() { * public Object transform(Object mapKey) { * return new File(mapKey); * } * } * SortedMap lazy = MapUtils.lazySortedMap(new TreeMap(), factory); * Object obj = lazy.get("C:/dev"); ** * After the above code is executed, obj will contain
* a new File instance for the C drive dev directory.
* Furthermore, that File instance is the value for the
* "C:/dev" key in the map.
* * If a lazy map is wrapped by a synchronized map, the result is a simple * synchronized cache. When an object is not is the cache, the cache itself * calls back to the factory Transformer to populate itself, all within the * same synchronized block. * * @param map the map to make lazy, must not be null * @param transformerFactory the factory for creating new objects, must not be null * @return a lazy map backed by the given map * @throws IllegalArgumentException if the Map or Transformer is null */ public static SortedMap lazySortedMap(SortedMap map, Transformer transformerFactory) { return LazySortedMap.decorate(map, transformerFactory); } } |
... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.