Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How list differ from map?

Tags:

java

In java, List and Map are using in collections. But i couldn't understand at which situations we should use List and which time use Map. What is the major difference between both of them?

like image 221
Vicky Avatar asked May 03 '12 06:05

Vicky


3 Answers

Now would be a good time to read the Java collections tutorial - but fundamentally, a list is an ordered sequence of elements which you can access by index, and a map is a usually unordered mapping from keys to values. (Some maps preserve insertion order, but that's implementation-specific.)

It's usually fairly obvious when you want a key/value mapping and when you just want a collection of elements. It becomes less clear if the key is part of the value, but you want to be able to get at an item by that key efficiently. That's still a good use case for a map, even though in some senses you don't have a separate collection of keys.

There's also Set, which is a (usually unordered) collection of distinct elements.

like image 51
Jon Skeet Avatar answered Oct 22 '22 15:10

Jon Skeet


Map is for Key:Value pair kind of data.for instance if you want to map student roll numbers to their names.

List is for simple ordered collection of elements which allow duplicates. for instance to represent list of student names.

like image 38
Balaswamy Vaddeman Avatar answered Oct 22 '22 15:10

Balaswamy Vaddeman


Map Interface A Map cares about unique identifiers. You map a unique key (the ID) to a specific value, where both the key and the value are, of course, objects. The Map implementations let you do things like search for a value based on the key, ask for a collection of just the values, or ask for a collection of just the keys. Like Sets, Maps rely on the equals() method to determine whether two keys are the same or different.

List Interface A List cares about the index. The one thing that List has that non-lists don't have is a set of methods related to the index. Those key methods include things like get(int index), indexOf(Object o), add(int index, Object obj), and so on. All three List implementations are ordered by index position—a position that you determine either by setting an object at a specific index or by adding it without specifying position, in which case the object is added to the end.

like image 1
Guneet Avatar answered Oct 22 '22 15:10

Guneet