difference between list set and map in java

List, Set and Map are the interfaces which implements Collection interface. Lets discuss the differences 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. It doesn’t affect the previous values and indexes.
Set doesn’t allow duplicate elements.
Map stores the elements as key & value pair. Map doesn’t allow duplicate keys but it allows duplicate values.

2) Null values: 

List allows any number of null values.
Set allows only one single null value.
Map can have only one single null key and any number of null values.

3) Insertion Order:

List maintains the insertion order.
Set doesn’t maintain any order. But 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.

4) Commonly used classes:

List: ArrayList, LinkedList etc.
Set: HashSet, LinkedHashSet, TreeSet etc.
Map: HashMap, TreeMap, LinkedHashMap etc.

When to use List, Set and Map in Java?

1) If the requirement is to have no duplicate values then Set should be the better choice.
2) If the requirement wants more search operations based on index then List (Ex: ArrayList) is a better choice.
3) If you want to maintain insertion order then List is a preferred choice.
4) If the requirement is to have the key & value pair mappings then Map is your best choice.


Tags: List in Java, Set in Java, Map in Java, ArrayList in Java, list of objects in java.