Difference Between Set, List and Map in Java

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 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 about the difference between set, list and map in Java.

 

Differences between Set, List 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 set does not. Similarly, Map will hold two object per entry, key and value. Here the value can be duplicate but the keys are always unique.

 

Order

When 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 comparator.

 

Null Elements

List allows many null elements as it permits duplicates but set can have only one null element. Map can have many null values but can have only one null key.

 

When to Use Set, List and Map in Java

 

  • When there is a need to access elements frequently using 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 set, list and map in java and also must have got a perfect knowledge about when to use each one. This portion will be taught in detail in the Java Tutorials.

 

Related posts

Leave a Comment