List, Set and Map are the interfaces which implements Collection interface. Here we will discuss difference between List Set and Map in Java.
List Vs Set Vs Map
1) Duplicity: List allows duplicate elements. Any number of duplicate elements can be inserted into the list without affecting the same existing values and their indexes.
Set doesn’t allow duplicates. Set and all of the classes which implements Set interface should have unique elements.
Map stored the elements as key & value pair. Map doesn’t allow duplicate keys while it allows duplicate values.
2) Null values: List allows any number of null values.
Set allows single null value at most.
Map can have single null key at most and any number of null values.
3) Order: List and all of its implementation classes maintains the insertion order.
Set doesn’t maintain any order; still few of its classes sort the elements in an order such as LinkedHashSet maintains the elements in insertion order.
Similar to Set Map also doesn’t stores the elements in an order, however few of its classes does the same. For e.g. TreeMap sorts the map in the ascending order of keys and LinkedHashMap sorts the elements in the insertion order, the order in which the elements got added to the LinkedHashMap.
4) Commonly used classes:
List: ArrayList, LinkedList etc.
Set: HashSet, LinkedHashSet, TreeSet, SortedSet etc.
Map: HashMap, TreeMap, WeakHashMap, LinkedHashMap, IdentityHashMap etc.
When to use List, Set and Map in Java?
1) If you do not want to have duplicate values in the database then Set should be your first choice as all of its classes do not allow duplicates.
2) If there is a need of frequent search operations based on the index values then List (ArrayList) is a better choice.
3) If there is a need of maintaining the insertion order then also the List is a preferred collection interface.
4) If the requirement is to have the key & value mappings in the database then Map is your best bet.
Helpful information! Concise and explicit! Thanks)
Bhaskar M says
Difference between list set and map in java?
List, Set and Map are interfaces which implements Collection interface.
Sorry an interface (List/Set/Map) can never implement another interface (Collection). But, extends.
Chaitanya Singh says
Good Point. Thanks for pointing that out. Will edit it. Lets see how many will figure this out.
Nice Explanation: Really I found the exact where we can use the Collections, Like Map,Set and List.
Shubham Singh Parmar says
IF HashSet internally implements HashMap, then what is the purpose of HashSet as a separate Class when ultimately every task is done by HashMap itself? Can anyone please sort this confusion for me????
HashSet is ultimately different from HashMap which holds key value pair i.e. Each value has it own key. whereas HashSet is used to store unique set of values without any key,