Collections in Java: Types, Methods and Examples

A collection in Java is an object that stores a group of elements and provides standard operations to add, remove, search and sort them. Collections in Java live in the java.util package and are organised into four main types: List, Set, Queue and Map, each solving a different data-management problem.

  • Key Takeaway 1: All core collection interfaces and classes sit in the java.util package, introduced in Java 1.2.
  • Key Takeaway 2: Collection (singular) is an interface; Collections (plural) is a utility class with static helper methods.
  • Key Takeaway 3: The four main types are List, Set, Queue and Map, each suited to a different problem.
  • Key Takeaway 4: Using generics with collections (for example, List<String>) prevents ClassCastException at runtime.
  • Key Takeaway 5: Choosing the wrong collection type is one of the most common performance mistakes in Java interviews and production code.

What Collections in Java Are

Before the Java Collections Framework arrived, developers managed groups of objects with plain arrays, which are fixed in size and painful to resize. The framework, standardised in Java 1.2, replaced that with a set of interfaces and classes that handle resizing, ordering and uniqueness automatically.

Every collection in Java is part of a hierarchy rooted at the Iterable interface. Below that sits the Collection interface, which is then extended by List, Set and Queue. Map is separate because it stores key-value pairs rather than single elements, but it is still part of the same framework.

According to the Oracle Java documentation, the Collections Framework was designed to reduce programming effort, increase performance and promote software reuse. Those three goals remain relevant whether you are writing a college assignment or a production microservice at a startup in Bengaluru.

Java consistently ranks among the top three languages in the TIOBE Index. The Stack Overflow Developer Survey reported that Java was used by approximately 30% of professional developers globally in its most recent annual edition, placing it among the five most-used languages for over a decade. Collections are central to virtually every Java project, which is why interviewers at TCS, Infosys, Wipro and product companies test them heavily.

According to NASSCOM’s annual IT workforce report, Java remains the most in-demand backend language for Indian IT services hiring, appearing in over 60% of backend developer job descriptions on portals like Naukri and LinkedIn India. If you are studying programming as part of a BSc Computer Science or MCA programme at universities such as Anna University or Mumbai University, you will encounter collections in your data structures course and again in Java application development.

The java.util Package

All the core collection interfaces and classes live in java.util. You import what you need at the top of your file: import java.util.ArrayList; or import java.util.*; if you need several classes at once. The collections package in Java is not a separate download; it ships with every standard JDK installation.

There is also java.util.concurrent for thread-safe collections like ConcurrentHashMap and CopyOnWriteArrayList, but those are advanced topics. Stick with java.util until you are comfortable with the basics.

Why Generics Matter Here

Generics let you specify the type of element a collection holds: List<Integer> instead of a raw List. Without generics, the compiler cannot catch type errors, and you will get a ClassCastException at runtime. Note that storing primitives like int or double in a collection requires autoboxing into their wrapper classes (Integer, Double), which Java handles automatically but which adds a small overhead worth knowing about.

Understanding how to handle runtime errors is just as important as understanding collections. Our guide on Java exceptions and common runtime errors covers exactly what happens when you misuse a collection and how to recover from it.

Collection vs Collections in Java

This is the question that trips up almost every Java beginner, and it comes up in interviews constantly.

Feature Collection (interface) Collections (class)
Type Interface Utility class (final)
Package java.util java.util
Purpose Defines the contract for all collection types Provides static helper methods to operate on collections
Can be instantiated? No (it is an interface) No (all methods are static)
Example usage Collection<String> c = new ArrayList<>(); Collections.sort(list);
Extends / Implements Extends Iterable Extends Object

Collection (singular) is the root interface. It declares methods like add(), remove(), size() and contains() that every implementing class must provide. Collections (plural) is a class full of static methods you call directly, like Collections.sort(myList) or Collections.shuffle(myList). You never create an instance of it.

Types of Collections in Java

The Java Collections Framework organises its types into four main groups. Each one solves a specific problem. Picking the right one is the real skill.

ArrayList and LinkedList: Java List Collection with Examples

A List maintains insertion order and allows duplicate elements. It is the most commonly used collection type. ArrayList is backed by a dynamic array: random access is fast (O(1)), but inserting or deleting in the middle is slow (O(n)). LinkedList is backed by a doubly-linked list, so insertions and deletions anywhere are fast (O(1)), but random access is slow (O(n)).

You can iterate over any List using a for-each loop: for (String name : students) { System.out.println(name); }. For most day-to-day use cases, like storing a list of student names or product IDs, ArrayList is your default choice.

Example: List<String> students = new ArrayList<>(); students.add("Priya"); students.add("Arjun"); students.add("Priya"); gives you three elements, with “Priya” appearing twice. That is perfectly valid with a List.

HashSet, LinkedHashSet and TreeSet: Java Set Collection

A Set stores unique elements only. If you try to add a duplicate, the collection silently ignores it. HashSet is the fastest for add/remove/contains operations (average O(1)) but gives no guarantee on order. LinkedHashSet preserves insertion order. TreeSet keeps elements sorted in natural order using the Comparable interface, or in a custom order if you supply a Comparator, at a cost of O(log n) per operation.

Use a Set when you need to track unique values, like a list of unique PIN codes or distinct error codes logged by your application.

Queue and PriorityQueue: FIFO and Priority-Based Processing

A Queue processes elements in FIFO order. LinkedList implements Queue, and PriorityQueue orders elements by priority rather than insertion order. A real use case: if you are building a print queue or a job scheduler for a college management system, a PriorityQueue lets high-priority jobs jump ahead without you writing the sorting logic yourself.

HashMap, LinkedHashMap and TreeMap: Java Map Key-Value Pairs

Map does not extend Collection, but it is part of the same framework. It stores data as key-value pairs where each key is unique. HashMap is the workhorse: fast average O(1) for get/put, unordered. LinkedHashMap maintains insertion order. TreeMap keeps keys sorted using Comparable or a custom Comparator.

Example: Map<Integer, String> rollBook = new HashMap<>(); rollBook.put(101, "Sneha"); rollBook.put(102, "Rahul");

If you are preparing for a career after MCA or aiming for a full-stack development role, you will use Maps constantly, especially when parsing JSON responses from REST APIs.

Quick Comparison: Which Java Collection to Use

Need Best Choice Reason
Ordered list with duplicates ArrayList Fast random access, resizable
Frequent insertions/deletions LinkedList O(1) insert/delete at known position
Unique elements only HashSet O(1) average for all operations
Unique elements, sorted TreeSet Natural/custom sort order via Comparable or Comparator
FIFO task processing LinkedList as Queue Efficient head/tail operations
Priority-based processing PriorityQueue Heap-based, automatic ordering
Key-value lookup HashMap O(1) average get/put
Key-value, sorted keys TreeMap Keys in natural or custom order

Collections Class Methods in Java with Examples

The Collections class in java.util is a final class with only static methods. You call them directly on the class, never on an instance. Here are the methods you will actually use.

Sorting and Ordering

Collections.sort(list) sorts a List in ascending natural order. It uses TimSort internally since Java 7, a stable algorithm that runs in O(n log n). Collections.sort(list, comparator) accepts a custom Comparator if you need a different order, like sorting students by grade descending. Collections.reverse(list) reverses the order in place. Collections.shuffle(list) randomises the order, useful for generating random quiz questions from a bank.

Finding Min, Max and Frequency

Collections.min(collection) and Collections.max(collection) return the smallest and largest elements using natural ordering or a provided Comparator. Collections.frequency(collection, object) counts how many times a specific object appears in the collection.

Filling, Copying and Replacing

Collections.fill(list, object) replaces every element in a list with the specified object. Collections.copy(dest, src) copies all elements from a source list to a destination list; the destination must be at least as large as the source, or you will get an IndexOutOfBoundsException. Collections.nCopies(n, object) returns an immutable list with n copies of the specified object, handy for initialising a list with default values.

Thread Safety and Immutability

Collections.synchronizedList(list) wraps any List in a thread-safe version. Similarly, Collections.synchronizedMap(map) and Collections.synchronizedSet(set) exist for their respective types. Collections.unmodifiableList(list) returns a read-only view; any attempt to modify it throws an UnsupportedOperationException.

One practical tip: do not reach for Collections.synchronizedList reflexively in concurrent code. According to the Oracle Java SE documentation, you still need to manually synchronise when iterating over the returned list, or you will get ConcurrentModificationException. Use CopyOnWriteArrayList from java.util.concurrent when iteration is frequent and modification is rare.

Binary Search

Collections.binarySearch(list, key) performs a binary search on a sorted list and returns the index of the key. The list must be sorted before you call this, or the result is undefined. This is O(log n) and significantly faster than a linear scan for large lists.

Understanding these tools is one of the software development tools to learn first that separates a developer who writes readable, maintainable code from one who reinvents sorting logic in every class.

If you are comparing career paths and wondering where Java fits in, our breakdown of full stack developer vs software developer roles gives a clear picture of what skills each path demands.

Summary of Key Collections Class Methods

Method What It Does Throws If
sort(list) Sorts list in ascending order Elements do not implement Comparable
reverse(list) Reverses list in place List is unmodifiable
shuffle(list) Randomises element order List is unmodifiable
min(collection) Returns smallest element Collection is empty
max(collection) Returns largest element Collection is empty
frequency(collection, obj) Counts occurrences of obj Never (returns 0 if not found)
fill(list, obj) Replaces all elements with obj List is unmodifiable
copy(dest, src) Copies src elements into dest dest is smaller than src
binarySearch(list, key) Finds index of key (list must be sorted) Undefined result if list not sorted
unmodifiableList(list) Returns read-only view Caller tries to modify it
synchronizedList(list) Returns thread-safe wrapper Never on creation

Strong collections knowledge also feeds directly into secure coding practices. When you build secure applications, whether in ethical hacking tooling, AI systems or blockchain smart contract backends, you need to manage data structures without leaking memory or introducing race conditions. If that path interests you, check out the CEH v13 AI online course at 3.0 University, which builds on programming fundamentals like these.

Wrapping up: Collections in Java are the backbone of almost every Java application you will write or maintain. Pick the right type for the problem, use generics to catch errors at compile time, and lean on the Collections utility class instead of writing sorting or searching logic yourself.

  1. This week: Write a small Java programme that stores a list of five Indian cities in an ArrayList, sorts them with Collections.sort(), then prints the result. Swap it for a TreeSet and observe what changes.
  2. Next: Read the Java exception handling guide to understand what goes wrong when you misuse collections and how to handle it gracefully.
  3. Career step: Explore 3.0 University’s online certification courses in Cybersecurity, Ethical Hacking, AI and Blockchain, where solid Java and data-structure skills translate directly into building secure, production-grade systems.

Frequently Asked Questions

What are collections in Java?

Collections in Java are objects that group multiple elements into a single unit. They are part of the Java Collections Framework in the java.util package and include data structures like List, Set, Queue and Map. The framework was introduced in Java 1.2 to replace error-prone array-based approaches with reusable, well-tested data structures.

What is the difference between Collection and Collections in Java?

Collection (singular) is a root interface that defines the contract all collection classes must follow, with methods like add(), remove() and size(). Collections (plural) is a final utility class with only static methods, such as Collections.sort() and Collections.reverse(), used to operate on existing collection objects. You cannot instantiate either one directly.

What are the types of collections in Java?

The four main types are List (ordered, allows duplicates), Set (unordered, unique elements only), Queue (FIFO or priority-based ordering) and Map (key-value pairs, unique keys). Each has multiple implementations: for example, List includes ArrayList and LinkedList, while Map includes HashMap, LinkedHashMap and TreeMap. Choosing the right type depends on your access patterns and ordering requirements.

What methods does the Collections class have?

The Collections class provides static methods including sort(), reverse(), shuffle(), min(), max(), frequency(), fill(), copy(), binarySearch(), unmodifiableList() and synchronizedList(). All methods are static, so you call them directly on the class name, for example Collections.sort(myList), without creating an instance.

Which package contains collections in Java?

The core collection interfaces and classes are in the java.util package, which ships with every standard JDK. Thread-safe and concurrent collection implementations, like ConcurrentHashMap and CopyOnWriteArrayList, live in the java.util.concurrent package. You import the specific class you need, for example import java.util.ArrayList;, or use import java.util.*; to import the whole package.

Which collection is fastest in Java?

For most read-heavy operations, HashMap and HashSet offer the fastest average performance at O(1) for get, put and contains. For list access by index, ArrayList is fastest at O(1). If you need sorted data, TreeMap or TreeSet are the right choice at O(log n), accepting a speed trade-off for ordering. The fastest collection depends entirely on your specific access pattern.

Last updated: June 2025. Reviewed by the 3University editorial team.

We create, review, and maintain educational content covering Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain, Web3, and emerging technologies.

Read More Articles