Class Maps<K,V>
- Type Parameters:
K- The key type.V- The value type.
Map instances with various configuration options.
This builder provides a flexible and type-safe way to construct maps with support for adding entries, other maps, sorting by keys, and applying modifiers like unmodifiable or sparse modes. It's particularly useful when constructing maps dynamically from multiple sources or with conditional entries.
Instances of this builder can be created using create(Class, Class) or the convenience method
CollectionUtils.mapb(Class, Class).
Features:
- Fluent API - all methods return
this for method chaining - Multiple add methods - single entries, pairs, other maps
- Arbitrary input support - automatic type conversion with
addAny(Object...) - Pair adding -
addPairs(Object...)for varargs key-value pairs - Filtering support - exclude unwanted entries via
filtered()orfiltered(BiPredicate) - Sorting support - natural key order or custom
Comparator - Sparse mode - return
null for empty maps - Unmodifiable mode - create immutable maps
- Custom conversion functions - type conversion via
keyFunction(Function)andvalueFunction(Function)
Examples:
Thread Safety:
This class is not thread-safe. Each builder instance should be used by a single thread or properly synchronized.
See Also:
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionAdds a single entry to this map.Appends the contents of the specified map into this map.Adds arbitrary values to this map.Adds a list of key/value pairs to this map.build()Builds the map.Builds the map as aFilteredMap.Builds the map and wraps it in aFluentMap.When specified,build()will return a thread-safe map.concurrent(boolean value) Sets whetherbuild()should return a thread-safe map.static <K,V> Maps<K, V> create()Static creator without explicit type parameters.static <K,V> Maps<K, V> Static creator.filtered()Applies a default filter that excludes common "empty" or "unset" values from being added to the map.filtered(BiPredicate<K, V> filter) Applies a filter predicate to entries when building the map.Sets both key and value conversion functions.keyFunction(Function<Object, K> keyFunction) Sets the key conversion function for converting keys inaddAny(Object...).ordered()When specified,build()will use aLinkedHashMapto preserve insertion order.ordered(boolean value) Sets whetherbuild()should use aLinkedHashMapto preserve insertion order.sorted()Converts the set into aSortedMap.sorted(Comparator<K> comparator) Converts the set into aSortedMapusing the specified comparator.sparse()When specified, thebuild()method will returnnull if the map is empty.When specified,build()will return an unmodifiable map.valueFunction(Function<Object, V> valueFunction) Sets the value conversion function for converting values inaddAny(Object...).
-
Constructor Details
-
Maps
Constructor.- Parameters:
keyType- The key type. Must not benull .valueType- The value type. Must not benull .
-
-
Method Details
-
create
Static creator.- Type Parameters:
K- Key type.V- Value type.- Parameters:
keyType- The key type. Must not benull .valueType- The value type. Must not benull .- Returns:
- A new builder.
-
create
Static creator without explicit type parameters.This is a convenience method that creates a builder without requiring explicit type parameters. The types will be inferred from usage context. Internally uses
Object.class for both key and value types, which allows any types to be added.Example:
Map<String, Integer>
map = Maps.create () .add("one" , 1) .add("two" , 2) .build();- Type Parameters:
K- Key type.V- Value type.- Returns:
- A new builder.
-
add
Adds a single entry to this map.Note: Filtering is applied at build time, not when adding entries.
- Parameters:
key- The map key.value- The map value.- Returns:
- This object.
-
addAll
Appends the contents of the specified map into this map.This is a no-op if the value is
null .Note: Filtering is applied at build time, not when adding entries.
- Parameters:
value- The map to add to this map.- Returns:
- This object.
-
addAny
Adds arbitrary values to this map.Objects can be any of the following:
- Maps of key/value types convertible to the key/value types of this map.
Each entry from the maps will be added using
add(Object, Object), which applies key/value function conversion if configured. Non-Map objects will cause aRuntimeExceptionto be thrown.- Parameters:
values- The values to add. Can containnull values (ignored).- Returns:
- This object.
- Throws:
RuntimeException- If a non-Map object is provided.
-
addPairs
Adds a list of key/value pairs to this map.- Parameters:
pairs- The pairs to add.- Returns:
- This object.
-
build
Builds the map.Applies filtering, sorting, ordering, concurrent, unmodifiable, and sparse options.
Map type selection:
- If
sorted()is set: UsesTreeMap(orConcurrentSkipListMapif concurrent) - If
ordered()is set: UsesLinkedHashMap(or synchronized LinkedHashMap if concurrent) - Otherwise: Uses
HashMap(orConcurrentHashMapif concurrent)
If filtering is applied, the result is wrapped in a
FilteredMap.- Returns:
- The built map, or
nullifsparse()is set and the map is empty.
- If
-
buildFluent
Builds the map and wraps it in aFluentMap.This is a convenience method that calls
build()and wraps the result in aFluentMap.Example:
import static org.apache.juneau.commons.utils.CollectionUtils.*; FluentMap<String,Integer>map =mapb (String.class , Integer.class ) .add("one" , 1) .add("two" , 2) .buildFluent(); -
buildFiltered
Builds the map as aFilteredMap.Map type selection:
- If
sorted()is set: UsesTreeMap(orConcurrentSkipListMapif concurrent) - If
ordered()is set: UsesLinkedHashMap(or synchronized LinkedHashMap if concurrent) - Otherwise: Uses
HashMap(orConcurrentHashMapif concurrent)
Example:
import static org.apache.juneau.commons.utils.CollectionUtils.*; FilteredMap<String,Integer>map =mapb (String.class , Integer.class ) .filtered((k, v) -> v !=null && v > 0) .add("a" , 5) .add("b" , -1)// Will be filtered out .buildFiltered();Note: If
unmodifiable()is set, the returned map will be wrapped in an unmodifiable view, which may cause issues if the FilteredMap tries to modify it internally. It's recommended to avoid usingunmodifiable()when calling this method.- Returns:
- The built map as a
FilteredMap, ornullifsparse()is set and the map is empty.
- If
-
keyFunction
Sets the key conversion function for converting keys inaddAny(Object...).The function is applied to each key when adding entries from maps in
addAny(Object...).- Parameters:
keyFunction- The function to convert keys. Must not benull .- Returns:
- This object.
-
valueFunction
Sets the value conversion function for converting values inaddAny(Object...).The function is applied to each value when adding entries from maps in
addAny(Object...).- Parameters:
valueFunction- The function to convert values. Must not benull .- Returns:
- This object.
-
functions
Sets both key and value conversion functions.Convenience method for setting both functions at once.
- Parameters:
keyFunction- The function to convert keys. Must not benull .valueFunction- The function to convert values. Must not benull .- Returns:
- This object.
-
filtered
Applies a default filter that excludes common "empty" or "unset" values from being added to the map.The following values are filtered out:
nullBoolean.FALSE- Numbers with
intValue() == -1 - Empty arrays
- Empty
Maps - Empty
Collections
Example:
import static org.apache.juneau.commons.utils.CollectionUtils.*; FluentMap<String,Object>map =mapb (String.class , Object.class ) .filtered() .add("name" ,"John" ) .add("age" , -1)// Filtered out at build time .add("enabled" ,false )// Filtered out at build time .add("tags" ,new String[0])// Filtered out at build time .build();- Returns:
- This object.
-
filtered
Applies a filter predicate to entries when building the map.The filter receives both the key and value of each entry. Entries where the predicate returns
truewill be kept; entries where it returnsfalsewill be filtered out.This method can be called multiple times. When called multiple times, all filters are combined using AND logic - an entry must pass all filters to be kept in the map.
Note: Filtering is applied at build time, not when adding entries.
Example:
import static org.apache.juneau.commons.utils.CollectionUtils.*;// Keep only non-null, non-empty string values Map<String,String>map =mapb (String.class , String.class ) .filtered((k, v) -> v !=null && !v.equals("" )) .add("a" ,"foo" ) .add("b" ,null )// Filtered out at build time .add("c" ,"" )// Filtered out at build time .build();// Multiple filters combined with AND Map<String,Integer>map2 =mapb (String.class , Integer.class ) .filtered((k, v) -> v !=null )// First filter .filtered((k, v) -> v > 0)// Second filter (ANDed with first) .filtered((k, v) -> ! k.startsWith("_" ))// Third filter (ANDed with previous) .add("a" , 5) .add("_b" , 10)// Filtered out (starts with "_") .add("c" , -1)// Filtered out (not > 0) .build();- Parameters:
filter- The filter predicate. Must not benull .- Returns:
- This object.
-
sorted
Converts the set into aSortedMap.Note: If
ordered()was previously called, calling this method will override it. The last method called (ordered()orsorted()) determines the final map type.- Returns:
- This object.
-
sorted
Converts the set into aSortedMapusing the specified comparator.Note: If
ordered()was previously called, calling this method will override it. The last method called (ordered()orsorted()) determines the final map type.- Parameters:
comparator- The comparator to use for sorting. Must not benull .- Returns:
- This object.
-
sparse
When specified, thebuild()method will returnnull if the map is empty.Otherwise
build()will never returnnull .- Returns:
- This object.
-
unmodifiable
When specified,build()will return an unmodifiable map.- Returns:
- This object.
-
concurrent
When specified,build()will return a thread-safe map.The thread-safety implementation depends on other settings:
- If
sorted()is set: UsesConcurrentSkipListMap - If
ordered()is set: UsesCollections.synchronizedMap(java.util.Map) - Otherwise: Uses
ConcurrentHashMap
This is useful when the map needs to be accessed from multiple threads.
Example:
import static org.apache.juneau.commons.utils.CollectionUtils.*;// Create a thread-safe map using ConcurrentHashMap Map<String,Integer>map =mapb (String.class , Integer.class ) .add("one" , 1) .add("two" , 2) .concurrent() .build();// Create a thread-safe ordered map Map<String,Integer>map2 =mapb (String.class , Integer.class ) .ordered() .concurrent() .add("one" , 1) .build();- Returns:
- This object.
- If
-
concurrent
Sets whetherbuild()should return a thread-safe map.The thread-safety implementation depends on other settings:
- If
sorted()is set: UsesConcurrentSkipListMap - If
ordered()is set: UsesCollections.synchronizedMap(java.util.Map) - Otherwise: Uses
ConcurrentHashMap
This is useful when the map needs to be accessed from multiple threads.
Example:
import static org.apache.juneau.commons.utils.CollectionUtils.*;// Conditionally create a thread-safe map Map<String,Integer>map =mapb (String.class , Integer.class ) .add("one" , 1) .concurrent(needsThreadSafety ) .build();- Parameters:
value- Whether to make the map thread-safe.- Returns:
- This object.
- If
-
ordered
When specified,build()will use aLinkedHashMapto preserve insertion order.If not specified, a
HashMapis used by default (no guaranteed order).Note: If
sorted()was previously called, calling this method will override it. The last method called (ordered()orsorted()) determines the final map type.Example:
import static org.apache.juneau.commons.utils.CollectionUtils.*;// Create an ordered map (preserves insertion order) Map<String,Integer>map =mapb (String.class , Integer.class ) .ordered() .add("one" , 1) .add("two" , 2) .build();- Returns:
- This object.
-
ordered
Sets whetherbuild()should use aLinkedHashMapto preserve insertion order.If
false (default), aHashMapis used (no guaranteed order). Iftrue , aLinkedHashMapis used (preserves insertion order).Note: If
sorted()was previously called, calling this method withtrue will override it. The last method called (ordered()orsorted()) determines the final map type.Example:
import static org.apache.juneau.commons.utils.CollectionUtils.*;// Conditionally create an ordered map Map<String,Integer>map =mapb (String.class , Integer.class ) .ordered(preserveOrder ) .add("one" , 1) .build();- Parameters:
value- Whether to preserve insertion order.- Returns:
- This object.
-