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]);
}
I like Kango_V's answer, but I think it's too complex. I think this is simpler - maybe too simple. If inclined, you could replace String with a Generic marker, and make it work for any Key type.
Used like this:
A
List
andMap
are conceptually different. AList
is an ordered collection of items. The items can contain duplicates, and an item might not have any concept of a unique identifier (key). AMap
has values mapped to keys. Each key can only point to one value.Therefore, depending on your
List
's items, it may or may not be possible to convert it to aMap
. Does yourList
's items have no duplicates? Does each item have a unique key? If so then it's possible to put them in aMap
.Here's a little method I wrote for exactly this purpose. It uses Validate from Apache Commons.
Feel free to use it.
Universal method
Assuming of course that each Item has a
getKey()
method that returns a key of the proper type.You can leverage the streams API of Java 8.
For more details visit: http://codecramp.com/java-8-streams-api-convert-list-map/