Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)

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

}

1 Answer

0 votes
by (46k points)

List<Item> list;

Map<Key,Item> map = new HashMap<Key,Item>();

for (Item i : list) map.put(i.getKey(),i);

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

Related questions

+1 vote
2 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...