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]);
}
Many solutions come to mind, depending on what you want to achive:
Every List item is key and value
List elements have something to look them up, maybe a name:
List elements have something to look them up, and there is no guarantee that they are unique: Use Googles MultiMaps
Giving all the elements the position as a key:
...
It really depends on what you want to achive.
As you can see from the examples, a Map is a mapping from a key to a value, while a list is just a series of elements having a position each. So they are simply not automatically convertible.
Since Java 8, the answer by @ZouZou using the
Collectors.toMap
collector is certainly the idiomatic way to solve this problem.And as this is such a common task, we can make it into a static utility.
That way the solution truly becomes a one-liner.
And here's how you would use it on a
List<Student>
:With java-8, you'll be able to do this in one line using streams, and the
Collectors
class.Short demo:
Output:
As noted in comments, you can use
Function.identity()
instead ofitem -> item
, although I findi -> i
rather explicit.And to be complete note that you can use a binary operator if your function is not bijective. For example let's consider this
List
and the mapping function that for an int value, compute the result of it modulo 3:When running this code, you'll get an error saying
java.lang.IllegalStateException: Duplicate key 1
. This is because 1 % 3 is the same as 4 % 3 and hence have the same key value given the key mapping function. In this case you can provide a merge operator.Here's one that sum the values;
(i1, i2) -> i1 + i2;
that can be replaced with the method referenceInteger::sum
.which now outputs:
Hope it helps! :)
Apache Commons MapUtils.populateMap
If you don't use Java 8 and you don't want to use a explicit loop for some reason, try
MapUtils.populateMap
from Apache Commons.MapUtils.populateMap
Say you have a list of
Pair
s.And you now want a Map of the
Pair
's key to thePair
object.gives output:
That being said, a
for
loop is maybe easier to understand. (This below gives the same output):