List, Set and Map - Difference Between Set, List and Map in Java

Interfaces in Java are similar to classes. An interface can be considered a reference type and interfaces has great significance in Java. Hence they are taught in depth in all java tutorials. Set, List and Map are three most important interface in java collection framework and the difference between these three is one of the most frequently asked questions in most of the Java tutorials.

In most of the interviews, the interviewer will ask when to use set, list and map and this question is aimed and finding whether the candidate has full knowledge about this interface in Java. In order to know the right answer, you should be aware of the difference between set, list and map in Java.

Differences between List, Set and Map in Java

As you are already aware, set, list and map are interfaces in Java and the differences between them can be verified on different metrics.

Duplicate Objects

When you look from the perspective of duplicate contents, List allows duplicate contents but the set does not. Similarly, Map will hold two objects per entry, key, and value. Here the value can be duplicate but the keys are always unique.

Order

When an order is considered as the metric, list ensures an order for the collection. The elements will be stored in the insertion order. Set will not guarantee any order. However, some set implementations such as “LinkedHashSet” maintains order. Similarly, “TreeSet and TreeMap” maintain order imposed by the comparator.

Null Elements

The list allows many null elements as it permits duplicates but the set can have only one null element. The map can have many null values but can have only one null key.

When to Use List, Set and Map in Java

  • When there is a need to access elements frequently using the index, then the best option is “List”. Its implementation “ArrayList” ensures a faster access.
  • When you want the elements stored to maintain the insertion order then also “List” will be the best option as it maintains an order for stored elements.
  • When the collection should be of unique elements and no duplicates are tolerated, then go with “Set”
  • When the data stored should be in the form of “Key” and “Value”, then the best option is “Map”.

Now you must have learned the differences between List, Set and Map in java and also must have got a perfect knowledge of when to use each one. This portion will be taught in detail in the Java Tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *