Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I didn't get the sense of Maps in Java. When is it recommended to use a Map instead of a List?

like image 316
JBeg Avatar asked Sep 22 '10 15:09

JBeg


People also ask

What is the difference between a map and a List?

Lists:: A list is an ordered collection of elements that are distinguished by their indices. List elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types. A map is a collection of key-value pairs where each unique key maps to a single value.

When to use a List vs Set vs map?

List in Java provides ordered and indexed collection which may contain duplicates. The Set interface provides an unordered collection of unique objects, i.e. Set doesn't allow duplicates, while Map provides a data structure based on key-value pair and hashing.

Which is faster map or List?

Map function is faster than list comprehension when the formula is already defined as a function earlier. So, that map function is used without lambda expression.

Which is faster List or map in Java?

The ArrayList has O(n) performance for every search, so for n searches its performance is O(n^2). The HashMap has O(1) performance for every search (on average), so for n searches its performance will be O(n). While the HashMap will be slower at first and take more memory, it will be faster for large values of n.


1 Answers

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.

like image 168
Tony Ennis Avatar answered Sep 22 '22 10:09

Tony Ennis