I would like to apply a function to a Java collection, in this particular case a map. Is there a nice way to do this? I have a map and would like to just run trim() on all the values in the map and have the map reflect the updates.
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction.
The get() method of Map interface in Java is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
Map put() Method in Java with Examples Parameters: This method has two arguments, key and value where key is the left argument and value is the corresponding value of the key in the map. Returns: This method returns returns previous value associated with the key if present, else return -1.
put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.
With Java 8's lambdas, this is a one liner:
map.replaceAll((k, v) -> v.trim());
For the sake of history, here's a version without lambdas:
public void trimValues(Map<?, String> map) { for (Map.Entry<?, String> e : map.entrySet()) { String val = e.getValue(); if (val != null) e.setValue(val.trim()); } }
Or, more generally:
interface Function<T> { T operate(T val); } public static <T> void replaceValues(Map<?, T> map, Function<T> f) { for (Map.Entry<?, T> e : map.entrySet()) e.setValue(f.operate(e.getValue())); } Util.replaceValues(myMap, new Function<String>() { public String operate(String val) { return (val == null) ? null : val.trim(); } });
I don't know a way to do that with the JDK libraries other than your accepted response, however Google Collections lets you do the following thing, with the classes com.google.collect.Maps
and com.google.common.base.Function
:
Map<?,String> trimmedMap = Maps.transformValues(untrimmedMap, new Function<String, String>() { public String apply(String from) { if (from != null) return from.trim(); return null; } }
The biggest difference of that method with the proposed one is that it provides a view to your original map, which means that, while it is always in sync with your original map, the apply
method could be invoked many times if you are manipulating said map heavily.
A similar Collections2.transform(Collection<F>,Function<F,T>)
method exists for collections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With