javalistdata-structureshashmapjava-stream

How to convert List to Map?


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]);
}

Solution

  • List<Item> list;
    Map<Key,Item> map = new HashMap<Key,Item>(list.size());
    for (Item i : list) map.put(i.getKey(),i);
    

    Assuming of course that each Item has a getKey() method that returns a key of the proper type.