Skip to content

Java collections

Collections are collection of classes and interfaces—that Java provides to help you store, organize, and manipulate groups of objects. Whether you're dealing with lists, sets, maps, or queues, Java collections have got you covered!

Imagine you're organizing a treasure trove of precious gems. You need a way to keep track of each gem's type, value, and rarity. That's where Java collections come in handy! They offer various containers, each tailored to suit different needs.

Most commonly used Java collections:

  1. Lists: Like a neatly arranged shelf in a library, lists allow you to store objects in a specific order. You can access elements by their index and easily add, remove, or modify them.

  2. Sets: Picture a chest filled with unique treasures—sets ensure that each object you add is distinct. They're perfect for tasks that require uniqueness, such as keeping track of unique values or eliminating duplicates.

  3. Maps: Ever used a treasure map to find buried loot? Maps in Java are similar—they allow you to associate keys with values, creating a powerful tool for storing and retrieving data based on unique identifiers.

  4. Queues: Imagine a line of adventurers waiting to claim their share of treasure. Queues in Java represent a first-in-first-out (FIFO) ordering, making them ideal for scenarios like task scheduling or event handling.

Simple example:

java
import java.util.ArrayList;
import java.util.List;

public class CollectionsExample {
    public static void main(String[] args) {
        // Create a list to store gems
        List<String> gemList = new ArrayList<>();

        // Add some gems to the list
        gemList.add("Diamond");
        gemList.add("Ruby");
        gemList.add("Emerald");

        // Print all the gems in the list
        System.out.println("Gems in the treasure trove:");
        for (String gem : gemList) {
            System.out.println(gem);
        }
    }
}

In this example, we've created a list to store gems and populated it with a few precious stones. We then loop through the list and print out each gem's name. It's like taking inventory of the treasures we've gathered!

Collections interfaces

A table listing out all the main collection interfaces in Java:

InterfaceDescription
CollectionThe root interface in the collection hierarchy.
ListAn ordered collection that allows duplicate elements.
SetA collection that does not allow duplicate elements.
QueueA collection used for holding elements prior to processing.
DequeA linear collection used for holding elements prior to processing.
MapAn object that maps keys to values, also known as an associative array.
SortedSetA set that maintains its elements in ascending order.
SortedMapA map that maintains its mappings in ascending order of keys.
NavigableSetA SortedSet extended with navigation methods.
NavigableMapA SortedMap extended with navigation methods.
BlockingQueueA Queue that supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.
TransferQueueA BlockingQueue in which producers may wait for consumers to receive elements.
BlockingDequeA Deque that supports operations that wait for the deque to become non-empty when retrieving an element, and wait for space to become available in the deque when storing an element.
ListIteratorAn iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list.

Collection classes

Following tables consist of implementations of collection interfaces

Collection InterfaceDescription
ListOrdered collection that allows duplicate elements. Implementations include ArrayList, LinkedList, Vector, and Stack.
SetCollection that does not allow duplicate elements. Implementations include HashSet, LinkedHashSet, and TreeSet.
MapCollection that maps keys to values. Implementations include HashMap, LinkedHashMap, TreeMap, and HashTable.
QueueCollection designed for holding elements prior to processing. Implementations include LinkedList, PriorityQueue, and ArrayDeque.
DequeA double-ended queue that supports insertion and removal at both ends. Implementations include ArrayDeque and LinkedList.
CollectionThe root interface in the collection hierarchy. It provides basic operations such as add, remove, and contains. Implementations include ArrayList, LinkedList, HashSet, and others.

Methods of the Collection interface

MethodDescription
int size()Returns the number of elements in the collection.
boolean isEmpty()Returns true if the collection contains no elements.
boolean contains(Object o)Returns true if the collection contains the specified element.
boolean add(E e)Adds the specified element to the collection.
boolean remove(Object o)Removes the specified element from the collection.
void clear()Removes all elements from the collection.
Iterator<E> iterator()Returns an iterator over the elements in the collection.
Object[] toArray()Returns an array containing all of the elements in the collection.
<T> T[] toArray(T[] a)Returns an array containing all of the elements in the collection; the runtime type of the returned array is that of the specified array.
boolean containsAll(Collection<?> c)Returns true if the collection contains all of the elements in the specified collection.
boolean addAll(Collection<? extends E> c)Adds all of the elements in the specified collection to the collection.
boolean removeAll(Collection<?> c)Removes all of the elements from the collection that are also contained in the specified collection.
boolean retainAll(Collection<?> c)Retains only the elements in the collection that are contained in the specified collection.
boolean equals(Object o)Compares the specified object with the collection for equality.
int hashCode()Returns the hash code value for the collection.

These methods provide a comprehensive set of operations for working with collections in Java, allowing you to manipulate elements, check for containment, and perform other common tasks.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.