I've just started looking at Java 8 and to try out lambdas I thought I'd try to rewrite a very simple thing I wrote recently. I need to turn a Map of String to Column into another Map of String to Column where the Column in the new Map is a defensive copy of the Column in the first Map. Column has a copy constructor. The closest I've got so far is:
Map<String, Column> newColumnMap= new HashMap<>();
originalColumnMap.entrySet().stream().forEach(x -> newColumnMap.put(x.getKey(), new Column(x.getValue())));
but I'm sure there must be a nicer way to do it and I'd be grateful for some advice.
You could use a Collector:
If you don't mind using 3rd party libraries, my cyclops-react lib has extensions for all JDK Collection types, including Map. You can directly use the map or bimap methods to transform your Map. A MapX can be constructed from an existing Map eg.
If you also wish to change the key you can write
bimap can be used to transform the keys and values at the same time.
As MapX extends Map the generated map can also be defined as
The way without re-inserting all entries into the new map should be the fastestit won't becauseHashMap.clone
internally performs rehash as well.Here is another way that gives you access to the key and the value at the same time, in case you have to do some kind of transformation.
You can use the
forEach
method to do what you want.What you're doing there is:
Which we can simplify into a lambda:
And because we're just calling an existing method we can use a method reference, which gives us:
Keep it Simple and use Java 8:-