Set, List and Map are three important interfaces of the Java collection framework, and the difference between Set, List, and Map in Java is one of the most frequently asked Java Collection interview questions. Sometimes this question is asked as When to use List, Set and Map in Java. Clearly, the interviewer is looking to know that whether you are familiar with the fundamentals of the Java collection framework or not. In order to decide when to use List, Set or Map, you need to know what are these interfaces and what functionality they provide. List in Java provides ordered and indexed collection which may contain duplicates.
The Set interface provides an unordered collection of unique objects, i.e. Set doesn't allow duplicates, while Map provides a data structure based on key-value pair and hashing.
All three List, Set, and Map are interfaces in Java and there are many concrete implementations of them are available in Collection API. ArrayList and LinkedList are the two most popular used List implementations while LinkedHashSet, TreeSet, and HashSet are frequently used Set implementations.
In this Java article, we will see the difference between Map, Set, and List in Java and learn when to use List, Set, or Map.
The Set interface provides an unordered collection of unique objects, i.e. Set doesn't allow duplicates, while Map provides a data structure based on key-value pair and hashing.
All three List, Set, and Map are interfaces in Java and there are many concrete implementations of them are available in Collection API. ArrayList and LinkedList are the two most popular used List implementations while LinkedHashSet, TreeSet, and HashSet are frequently used Set implementations.
In this Java article, we will see the difference between Map, Set, and List in Java and learn when to use List, Set, or Map.
By the way, if you are new to Java development, I would suggest you join a comprehensive Java course like The Complete Java Masterclass on Udemy to learn essential Java concepts in-depth, including Collection classes. This 80-hour course is most up-to-date as well as very affordable as you can buy in just $10 on Udemy sales.
Set vs List vs Map in Java
As I said Set, List and Map are interfaces, which define core contracts e.g. a Set contract says that it can not contain duplicates. Based on our knowledge of List, Set and Map let's compare them on different metrics.
1.Duplicate Objects
The main difference between the List and Set interface in Java is that List allows duplicates while Set doesn't allow duplicates. All implementation of Set honor this contract.
While a Map holds two objects per Entry e.g. a key and a value and It may contain duplicate values but keys are always unique. See here for more differences between List and Set data structure in Java.
While a Map holds two objects per Entry e.g. a key and a value and It may contain duplicate values but keys are always unique. See here for more differences between List and Set data structure in Java.
2. Order
Another key difference between List and Set is that List is an ordered collection, List's contract maintains insertion order or element. Set is an unordered collection, you get no guarantee on which order element will be stored.
Though some of the Set implementations e.g. LinkedHashSet maintains order. Also, SortedSet and SortedMapl like TreeSet and TreeMap maintain a sorting order, imposed by using Comparator or Comparable.
Though some of the Set implementations e.g. LinkedHashSet maintains order. Also, SortedSet and SortedMapl like TreeSet and TreeMap maintain a sorting order, imposed by using Comparator or Comparable.
You can also further see, Java Collections: Fundamentals, an online course from Pluralsight by Richard Warburton. Pluralsight offers a 10-day free trial period, in which you can access many more advanced Java courses.
3. Null elements
The list allows null elements and you can have many null objects in a List because it also allowed duplicates. Set just allow one null element as there is no duplicate permitted while in Map you can have null values and at most one null key.
Worth noting is that Hashtable doesn't allow null key or values but HashMap allows null values and one null key. This is also the main difference between these two popular implementations of Map interface, aka HashMap vs Hashtable.
Worth noting is that Hashtable doesn't allow null key or values but HashMap allows null values and one null key. This is also the main difference between these two popular implementations of Map interface, aka HashMap vs Hashtable.
4. Useful implementations
The most popular implementations of the List interface in Java are ArrayList, LinkedList, and Vector class. ArrayList is more general-purpose and provides random access with index, while LinkedList is more suitable for frequently adding and removing elements from List.Vector is a synchronized counterpart of ArrayList. On the other hand, the most popular implementations of the Set interface are HashSet, LinkedHashSet, and TreeSet. The first one is a general-purpose Set which is backed by HashMap, see how HashSet works internally in Java for more details.
It also doesn't provide any ordering guarantee but LinkedHashSet does provide ordering along with uniqueness offered by the Set interface.
Third implementation TreeSet is also an implementation of the SortedSet interface, hence it keeps elements in a sorted order specified by compare() or compareTo() method.
Now the last one, the most popular implementation of Map interface is HashMap, LinkedHashMap, Hashtable, and TreeMap.
The first one is the non-synchronized general-purpose Map implementation while Hashtable is its synchronized counterpart, both don't provide any ordering guarantee which comes from LinkedHashMap. Just like TreeSet, TreeMap is also a sorted data structure and keeps keys in sorted order (see Java Collections from basics to Advanced Udemy course to learn more about it)
When to use List, Set, and Map in Java? Example
Based upon our understanding of the difference between Set, List and Map we can now decide when to use List, Set or Map in Java.
1. If you need to access elements frequently by using the index than List is a way to go. Its implementation e.g. ArrayList provides faster access if you know the index.
2. If you want to store elements and want them to maintain an order on which they are inserted into a collection then go for List again, as List is an ordered collection and maintain insertion order.
3. If you want to create a collection of unique elements and don't want any duplicate then choosing any Set implementation e.g. HashSet, LinkedHashSet or TreeSet.
All Set implementation follow there general contract e.g. uniqueness but also add addition feature e.g. TreeSet is a SortedSet and elements stored on TreeSet can be sorted by using Comparator or Comparable in Java. LinkedHashSet also maintains insertion order.
All Set implementation follow there general contract e.g. uniqueness but also add addition feature e.g. TreeSet is a SortedSet and elements stored on TreeSet can be sorted by using Comparator or Comparable in Java. LinkedHashSet also maintains insertion order.
4. If you store data in form of key and value than Map is the way to go. You can choose from Hashtable, HashMap, TreeMap based upon your subsequent need. In order to choose between the first two see the difference between HashSet and HashMap in Java.
That's all about the difference between Set, List, and Map in Java. All three are the most fundamental interface of the Java Collection framework and any Java developer should know their distinguish feature and given a situation should be able to pick the right Collection class to use.
It's also good to remember the difference between there implementation e.g. When to use ArrayList and LinkedList, HashMap vs Hashtable or When to use Vector or ArrayList etc. Collection API is huge and it's difficult to know every bits and piece but at the same time, there is no excuse for not knowing fundamentals like the difference between Set, List, and Map in Java.
Related Java Collection Articles you may like
- Difference between ConcurrentHashMap and HashMap in Java (answer)
- My favorite Courses to learn Java Collections (best courses)
- 5 Difference between HashMap and Hashtable in Java (answer)
- 10 Advanced Core Java Courses for Programmers (advanced courses)
- How to sort HashMap in Java by keys (example)
- 5 Free Java Programming Courses for Beginners (free courses)
- How to get key from HashMap by passing values (example)
- 50+ Java Collection Interview Questions with Answers (questions)
- 10 Example of Concurrent HashMap in Java (examples)
- 21 HashMap Interview questions for Java Programmers (questions)
- 5 Best Courses to learn Java Collection Framework (courses)
- 2 ways to sort HashMap in Java? (examples)
- How to sort HashMap by values in Java 8? (example)
- Difference between HashMap, LinkedHashMap, and TreeMap in Java (answer)
Thanks for
reading this article so far. If you find this Java interview question interesting and my explanation useful then please share it with your friends and colleagues. If you have you have any questions or feedback then please drop a note.
P. S. - If you are preparing for Java interviews and need more such questions for practice then you can also check out my book, Grokking the Java Interview which contains many such excellent core Java questions and covers all essential core Java topics like Collections, Multithreading, Core Java basics, design patterns, JDBC, and much more.
Nicely explained;
ReplyDeleteHope I read this before my interview.
good explanation helps us a lotttt
ReplyDeletesimple and detailed. thanks for the post
ReplyDeleteIts clear cut explanation.. Really helpful.. Thanks for post.
ReplyDeleteGood explanation.
ReplyDeleteThank You ... Its verynice explanation
ReplyDeleteI was asked this question yesterday on a interview and didn't know the difference between Set and Map :( Thanks!
ReplyDeleteExcellent explanation and really helpful for interviews.
ReplyDeleteSimply Superb and easy to understand
ReplyDeletethank you sir...simple upto the point explanation
ReplyDeletevery well explained!! helped a lot in concept just before interview!!
ReplyDeleteVery nice explained! thanks
ReplyDeleteVery well explained! thank alot
ReplyDeletewonderfully explained by the author
ReplyDeletegreat stuff ! Keep writing :)
ReplyDeleteI still find List as a duplicate of Map. Basically, if you set a key value of a given map to a sequence of integers from 0 to n (i-> value_i) it basically represent a List! Is there any reason (memory usage, etc) not to use Map all the times?
ReplyDeleteUsing keys instead of integers uses vast amounts of CPU time and memory.
Deletenicely explained
ReplyDeleteGood article
ReplyDeletenice
ReplyDeleteOne more Difference btwn HashSet and TreeSet :
ReplyDeleteIn HashSet Heterogeneous elements are allowed, but incase of TreeSet and TreeMap ony Homogeneous elements are allowed....
Very good article.
ReplyDeletewhat about Queue
ReplyDeleteyou explained Only List Set Map What about Queue
ReplyDeleteSure @hari, I will write about Queue interface as well.
DeleteCan u say about Hashcode
ReplyDeleteThank you !
ReplyDeleteOne of the best explaination.
ReplyDeleteSorry to be a pain but than is used as comparison and then used used to point a sequence... you use than instead of then...
ReplyDelete"1) If you need to access elements frequently by using the index than List is a way to go." -> Should be '(...) then List us a way to go.'
Hello Felipe, thanks, that's a mistake. I'll correct this article shortly, thanks for pointing that out.
DeleteThis article is absolutely amazing. It explains all the key features of different collections. I appreciate the time you put to write this awesome post. Can I also get the links of real world example of this collections? So we can compare them side by side.
ReplyDeletegreat stuff!!! Thanks.
ReplyDeletethanks..
ReplyDeleteSo amazing! Thank you so much!
ReplyDeleteThank you , short and simple explanation , love it !
ReplyDeleteglad you find this differences useful and like my explanation. happy to hear that.
Deletenice!
ReplyDeletelike the way things are put. Simple, Short, relevent.
ReplyDelete