Recently I have conversation with a colleague about what would be the optimal way to convert List
to Map
in Java and if there any specific benefits of doing so.
I want to know optimal conversion approach and would really appreciate if any one can guide me.
Is this good approach:
List<Object[]> results;
Map<Integer, String> resultsMap = new HashMap<Integer, String>();
for (Object[] o : results) {
resultsMap.put((Integer) o[0], (String) o[1]);
}
There is also a simple way of doing this using Maps.uniqueIndex(...) from Google guava libraries
Using Java 8 you can do following :
Value
can be any object you use.Without java-8, you'll be able to do this in one line Commons collections, and the Closure class
Alexis has already posted an answer in Java 8 using method
toMap(keyMapper, valueMapper)
. As per doc for this method implementation:So in case we are interested in a specific implementation of
Map
interface e.g.HashMap
then we can use the overloaded form as:Though using either
Function.identity()
ori->i
is fine but it seemsFunction.identity()
instead ofi -> i
might save some memory as per this related answer.A Java 8 example to convert a
List<?>
of objects into aMap<k, v>
:Code copied from:
https://www.mkyong.com/java8/java-8-convert-list-to-map/
Just in case this question isn't closed as a duplicate, the right answer is to use Google Collections: