List vs Map 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.


Java map: An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

Java list: An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

The difference is that they are different. Map is a mapping of key/values, a list of a list of items.


Its probably a good idea to revise Random Access Vs Sequential Access Data Structures. They both have different run time complexities and suitable for different type of contexts.

Tags:

Java

List

Map