Top 50+ Java Collections Imp Interview Questions (2024)
Top 50+ Java Collections Imp Interview Questions (2024)
Java Collection Framework was introduced in JDK 1.2 which contains all the
collection classes and interfaces. Java Collection is a framework that provides a
mechanism to store and manipulate the collection of objects. It allows developers to
access prepackaged data structures and algorithms for manipulating data.
Here, we’ve covered the 50+ Java Collections Interview Questions and Answers
tailored for both Fresher and experienced professionals, which cover everything
from basic to advanced Java collection concepts such as navigation collection,
WeakHashMap, streams Lambdas, etc.
We have divided the 50 questions into two parts: Experienced and Freshers. Let’s
begin with the questions for Freshers.
The term collection refers to a group of objects represented as one unit. Classes in
the Java collection class hierarchy are divided into two “root” interfaces: Collection
(java.util.Collection) and Map (java.util.Map). Terms that you will encounter while
learning about the collection in Java:
Spring
Hibernate
Struts
Google Web Toolkit (GWT)
JavaServer Faces (JSF)
Arrays Collection
Arrays are fixed in size that is once we The collection is growable in nature
create an array we can not increase or and is based on our requirements. We
decrease based on our requirements. can increase or decrease of size.
With respect to memory, Arrays are not With respect to memory, collections
recommended for use. are recommended for use.
For more information, refer to the article – Difference Between Arrays and
Collections in Java
The collection is known as the root of the collection hierarchy. Collections represent
groups of objects known as elements. The java platform does not provide any direct
implementation of this interface but the Collection interface is being implemented by
List and Set classes.
Collection interface
List interface
Set interface
Queue interface
Dequeue interface
Map interface
All classes and interfaces required by the collection framework are contained in the
utility package (java. util). Collection frameworks have an interface called an iterable
interface, which allows the iterator to iterate over all collections. In addition to this
interface, the main collection interface acts as a root for the collection framework. All
the collections extend this collection interface thereby extending the properties of the
iterator and the methods of this interface. The following figure illustrates the
hierarchy of the collection framework.
Java Collection Hierarchy
Consistent API: The API has a basic set of interfaces like Collection, Set, List, or
Map, all the classes (ArrayList, LinkedList, Vector, etc) that implement these
interfaces have some common set of methods.
Collection Collections
ArrayList LinkedList
This class works better when the This class works better when the
application demands storing the data application demands manipulation of the
and accessing it. stored data.
Java’s Collection framework uses iterators to retrieve elements one by one. This
iterator is universal since it can be used with any type of Collection object. Using
Iterator, we can perform both reading and removing operations. This is an improved
version of Enumeration with the addition of removing elements.
Syntax:
Note: Here “c” is any Collection object. itr is of type Iterator interface and refers to
“c”.
For more information, refer to the article – Difference between Iterator and
Enumeration
A major difference between a List and a Set is that a List can contain duplicate
elements while a set contains only unique elements. The list is Ordered and
maintains the order of the object to which they are added. The set is unordered.
List Set
Multiple null elements can be stored. Null elements can store only once.
For more information, refer to the article – Difference Between List and Set in
Java
13. What are the best practices for Java Collections Framework?
Following are some of the best practices while using Java Collections:
Programs should be written as interfaces, not implementations, so we can modify
the implementation later.
Whenever possible, use Generics to ensure type safety and avoid
ClassCastExceptions.
Choosing the appropriate type of collection based on the need. For example, if
the size is fixed, we might want to use an Array over an ArrayList. When iterating
over the Map, we should use LinkedHashMap. Set is the best way to avoid
duplicates.
Use immutable classes provided by JDK as keys in Map to avoid implementation
of hashCode() and equals().
In order to increase the readability of the code, we should use isEmpty() instead
of finding the size of the collection and comparing it to zero.
Rather than writing your own implementation, use the Collections utility class to
get read-only, Synchronized, or empty collections instead. It enhances code
reuse while resulting in greater stability.
PriorityQueues are used to process objects according to their priority. Queues follow
the First-In-First-Out algorithm, but sometimes the elements of the queue need to be
processed according to their priority, which is where PriorityQueue comes into play.
Priority queues are based on priority heaps.
The elements of the priority queue are ordered according to the natural ordering, or
by a Comparator provided at queue construction time, depending on which
constructor is used.
Priority Queues in Java
Declaration:
15. What is the difference between List, set, and map in java?
The list
Set implementation Map implementation classes are
implementation
classes are HashSet, HashMap, HashTable, TreeMap,
classes are Array
LinkedHashSet, and ConcurrentHashMap, and
List and
TreeSet. LinkedHashMap.
LinkedList.
For more information, refer to the article – Difference between List, Set, and
Map in Java
Stack Queue
The top of a stack always points to Two pointers are maintained for accessing
the last element in the list, which is queues. The front pointer points to the first
the only pointer used to access the inserted element, and the rear pointer
list. points to the last inserted element.
The BlockingQueue interface in Java is added in Java 1.5 along with various other
concurrent Utility classes like ConcurrentHashMap, Counting Semaphore,
CopyOnWriteArrrayList, etc. The BlockingQueue interface supports flow control (in
addition to queue) by introducing blocking if either BlockingQueue is full or empty.
A thread trying to enqueue an element in a full queue is blocked until some other
thread makes space in the queue, either by dequeuing one or more elements or
clearing the queue completely. Similarly, it blocks a thread trying to delete from an
empty queue until some other threads insert an item. BlockingQueue does not
accept a null value. If we try to enqueue the null item, then it throws
NullPointerException.
Usage of BlockingQueue
Blocking Queue in Java
Declaration:
Syntax :
For more information, refer to the article – equals() and hashCode() methods
in Java
ArrayList Vector
Iterator ListIterator
For more information, refer to the article – Difference Between an Iterator and
ListIterator
Syntax:
Syntax:
Iterator Enumeration
The iterator has the remove() Enumeration does not have the remove()
method. method.
The iterator can do modifications (e.g The enumeration interface acts as a read-
using the remove() method which only interface, one can not do any
removes the element from the modifications to the Collection while
Collection during traversal). traversing the elements of the Collection.
For more information, refer to the article – Difference between Iterator and
Enumeration
HashMap in Java
Syntax:
For more information, refer to the article – HashMap in Java with Examples
23. What are Collection Interfaces?
For Example, the HashSet class implements the Set interface which is a
subinterface of the Collection interface. If a collection implementation doesn’t
implement a particular operation, it should define the corresponding method to throw
UnsupportedOperationException.
In Java, the List interface allows the user to store an ordered collection of objects.
The list is the child interface of Collection. In Collection, a list is an ordered collection
of objects which can have duplicate values. Since List preserves the insertion order,
it allows positional access and insertion, which also allows duplicate values.
Syntax:
Java Course Java Arrays Java Strings Java OOPs Java Collection Java 8 Tutorial Java Multith
This list interface is implemented by various classes like ArrayList, Vector, Stack, etc.
Since all the subclasses implement the list, we can instantiate a list object with any
of these classes.
Example:
ArrayList
LinkedList
Vector
Stack
25. Write a program to convert a given array into a collection with the
asList() method.
Output
HashSet HashMap
For more information, refer to the article – Difference between HashMap and
HashSet
HashSet HashTable
HashTable
does not allow
HashSet allows NULL Elements NULL
Elements.
HashTable
Objects that you insert in HashSet are not guaranteed to be does not
inserted in the same order. Objects are inserted based on their maintain
hash code. LinkedHashSet can be used to maintain order. insertion
order.
put() method
is used to
add() method is used to insert into HashSet
insert into
HashTable
28. What is the default size of the load factor in the hashing-based
collection?
As the Load Factor increases, the capacity increases so that the operational
complexity of the HashMap remains O(1) if the ratio of the current element to the
initial capacity crosses the threshold. The meaning of operational complexity of O(1)
means the retrieval and insertion operations take constant time. The default load
factor size is 0.75. The default capacity is calculated by multiplying the initial
capacity by the load factor.
For more information, refer to the article – Load Factor in HashMap in Java
with Examples
Comparable
Comparator
Comparable Comparator
The actual class is modified by a The actual class is not modified by the
comparable interface Comparator interface.
Iterators in Java are used to iterate over the Collection objects. Fail-Fast iterators
immediately throw ConcurrentModificationException if there is a structural
modification of the collection. Structural modification means adding, or removing
any element from a collection while a thread is iterating over that collection. Iterator
on ArrayList and HashMap classes are some examples of fail-fast Iterator.
Fail- Fail-
Fast Safe
ConcurrentModificationException is
thrown while modifying the object No Exception is thrown
during the iteration process.
Fail-Fast does not allow modification Fail-Safe allows modification during the
during the process of iteration. process of iteration.
Examples: Examples:
For more information, refer to the article – Fail Fast and Fail Safe Iterators in
Java
31. Write a program to iterate the list using the lambda expression.
Syntax:
list_name.forEach(variable->{//block of code})
Java
// Class
class GFG {
Output
Geeks
for
Geeks
For more information, refer to the article – Iterate through List in Java
The hashtable class implements a hash table, which maps keys to values. Any non-
null object can be used as a key or as a value. To successfully store and retrieve
objects from a hashtable, the objects used as keys must implement the hashCode
method and the equals method. Below is the program to display the contents of a
HashTable using enumeration:
Java
// Java Program to Demonstrate Getting Values
// as an Enumeration of Hashtable class
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
// Main class
// EnumerationOnKeys
public class GFG {
Output
Geeks
for
Geeks
34. Write a program in java to get the collection view of the values
present in a HashMap.
Java
Output
Initial Mappings are: {0=Welcome, 1=to, 2=Geeks, 3=4, 4=Geeks}
The collection is: [Welcome, to, Geeks, 4, Geeks]
For more information, refer to the article – HashMap values() Method in Java
35. Write a program to join two ArrayList into one single ArrayList.
Java
// Java program to demonstrate
// How to join ArrayList
import java.util.*;
list_1.add("Geeks");
list_1.add("For");
list_1.add("ForGeeks");
list_2.add("GeeksForGeeks");
list_2.add("A computer portal");
Output
For more information, refer to the article – Join two ArrayLists in Java
36. How can you synchronize an ArrayList in Java?
Java
class GFG {
public static void main(String[] args)
{
// Non Synchronized ArrayList
List<String> list = new ArrayList<String>();
list.add("Eat");
list.add("Coffee");
list.add("Code");
list.add("Sleep");
list.add("Repeat");
Output
Eat
Coffee
Code
Sleep
Repeat
The properties class is a subclass of Hashtable. The properties class stores a list of
values whose key is a string and whose value is also a string. Properties can define
other properties class lists, but the default is properties.
39. What will happen if two different keys of HashMap return the same
hashcode()?
When two different keys of HashMap return the same hash code, they will end up in
the same bucket; therefore, collisions will occur. n case of collision, i.e. index of two
or more nodes is the same, nodes are joined by a link list i.e. the second node is
referenced by the first node and the third by the second, and so on.
Syntax:
Creating a Read-Only Collection involves restricting the object to only fetching the
data and not adding or removing data. Java has different methods for different
Collection types like unmodifiableCollection(), unmodifiableMap(),
ununmodifiableSet(), etc. java.util.The collections class defines all methods. The
unmodifiableCollection() method creates a Read-Only collection. It requires a
reference to the Collection class. If we have an object of Set Interface, we can use
ununmodifiableSet() to make Read-Only.
For more information, refer to the article – How to Make a Collection Read-
Only in Java?
PriorityQueue TreeSet
The data structure used by The data structure used by TreeSet is Set.
PriorityQueue is Queue
Diamond operators are used for simplifying the use of generics when creating
objects while avoiding unchecked warnings in a program. When the Diamond
operator was introduced in Java 7, we can create the object without mentioning the
generic type on the right side of the expression as shown below.
Syntax:
TreeMap stores the key-value pairs, but TreeMap sorts the keys ascending rather
than descending like HashMap. Depending on which constructor is used, TreeMap
will be sorted either based on its keys, or by a Comparator. In TreeMap, the
elements are sorted based on a Red-Black tree. A red-black tree is a self-balancing
binary search tree where each node has an extra bit, and that bit is often interpreted
as the color (red or black). These colors are used to ensure that the tree remains
balanced during insertions and deletions.
For more information, refer to the article – Internal Working of TreeMap in Java
The HashMap class provides Java’s Map interface by storing data in (Key, Value)
pairs and accessing them by an index of another type. To use this class it is
necessary to import java.util.HashMap package or its superclass.
There are numerous ways to iterate over HashMap of which 5 are listed below:
For more information, refer to the article – How to Iterate HashMap in Java
Syntax:
// K must extend Enum, which enforces the requirement that the keys must be
of the specified enum type.
Parameters:
EnumMap in Java
int hash
K key
V value
Node next
Hashing
Buckets
Index Calculation in Hashmap
Fail fast feature ensures that if iterator feels that modification of collection
would result in anomalous behaviour at any point of time in future, it fails
immediately.
Example:
Java
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
Iterator<Integer> it = arr.iterator();
while (it.hasNext()) {
if (it.next() == 2) {
// will not throw Exception
it.remove();
}
}
System.out.println(arr);
it = arr.iterator();
while (it.hasNext()) {
if (it.next() == 3) {
// will throw Exception on
// next call of next() method
arr.remove(3);
}
}
}
}
Output:
[1, 3, 4, 5]
Exception in thread "main"
java.util.ConcurrentModificationException
at
java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901
)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at FailFastExample.main(FailFastExample.java:28)
Conclusion
Java Collections is important to understand for Java developers or programmers
because Java is widely used in various industries. It’s important for developers to
have a solid understanding of core concepts of Java Collections. Java is one of the
most widely used languages in top companies such as Uber, Airbnb, Google, Netflix,
Instagram, Spotify, Amazon, etc. To get into these companies or any other IT
companies, you need to master these mostly asked Java Collections interview
questions in order to crack their Java-based online assessment and technical
interview.
There are many collections in Java but out of them most used collections are:
1. ArrayList
2. LinkedList
3. HashSet
4. Stack
No, HashMap can’t have duplicate keys. As HashMap is one of the collections
in Java, it stores the value in the form of key-value and every key has its own
value attached to it. So, as no key can have two value means we can’t have
duplicate keys in HashMap.
Want to be a master in Backend Development with Java for building robust and
scalable applications? Enroll in Java Backend and Development Live Course by
GeeksforGeeks to get your hands dirty with Backend Programming. Master the key
Java concepts, server-side programming, database integration, and more
through hands-on experiences and live projects. Are you new to Backend
development or want to be a Java Pro? This course equips you with all you need for
building high-performance, heavy-loaded backend systems in Java. Ready to take
your Java Backend skills to the next level? Enroll now and take your development
career to sky highs.
GeeksforGeeks 45
Similar Reads
Java.util.Collections.frequency() in Java
The method is a java.util.Collections class method. It counts the frequency of
the specified element in the given list. It override the equals() method to…
perform the comparison to check if the specified Object and the Object in the
2 min read
list are equal or not. Syntax: public static int frequency(Collection c, Object o)
parameters: c: Collection in which
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles