When to use a Map instead of a List in Java?

Say you have a bunch of students with names and student IDs. If you put them in a List, the only way to find the student with student_id = 300 is to look at each element of the list, one at a time, until you find the right student.

With a Map, you associate each student’s ID and the student instance. Now you can say, “get me student 300” and get that student back instantly.

Use a Map when you need to pick specific members from a collection. Use a List when it makes no sense to do so.

Say you had exactly the same student instances but your task was to produce a report of all students’ names. You’d put them in a List since there would be no need to pick and choose individual students and thus no need for a Map.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)