Collections Framework in Java

by Jasleen Chhabra | Updated on 24 August 2024

Table of Contents (Click any Topic to view first)

  1. Introduction to Collections (List, Set, Map)
  2. Iteration and Manipulation of Collections
  3. Generics in Collections

The Java Collections Framework provides a set of interfaces and classes for storing and manipulating groups of data as a single unit. This framework is part of the java.util package and includes various classes such as ArrayList, HashSet, HashMap, etc.

1. Introduction to Collections (List, Set, Map)

List

A List is an ordered collection that can contain duplicate elements. Elements in a list can be accessed by their position (index).

  • ArrayList: Resizable-array implementation of the List interface.

  • LinkedList: Doubly-linked list implementation of the List and Deque interfaces.

Example:

import java.util.ArrayList;

import java.util.List;

 

public class ListExample {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();

        list.add("Apple");

        list.add("Banana");

        list.add("Cherry");

        list.add("Apple"); // Duplicate element

 

        for (String fruit : list) {

            System.out.println(fruit);

        }

    }

}


Set

A Set is a collection that cannot contain duplicate elements. It models the mathematical set abstraction.

  • HashSet: Implements the Set interface, backed by a hash table (actually a HashMap instance).

  • LinkedHashSet: Hash table and linked list implementation of the Set interface, with predictable iteration order.

  • TreeSet: Implements the NavigableSet interface, backed by a TreeMap. The elements are ordered using their natural ordering or a comparator.

Example:

import java.util.HashSet;

import java.util.Set;

 

public class SetExample {

    public static void main(String[] args) {

        Set<String> set = new HashSet<>();

        set.add("Apple");

        set.add("Banana");

        set.add("Cherry");

        set.add("Apple"); // Duplicate element, will not be added

 

        for (String fruit : set) {

            System.out.println(fruit);

        }

    }

}


Map

A Map is an object that maps keys to values. A map cannot contain duplicate keys, and each key can map to at most one value.

  • HashMap: Hash table-based implementation of the Map interface.

  • LinkedHashMap: Hash table and linked list implementation of the Map interface, with predictable iteration order.

  • TreeMap: Red-Black tree-based implementation of the NavigableMap interface.

Example:

import java.util.HashMap;

import java.util.Map;

 

public class MapExample {

    public static void main(String[] args) {

        Map<String, Integer> map = new HashMap<>();

        map.put("Apple", 1);

        map.put("Banana", 2);

        map.put("Cherry", 3);

        map.put("Apple", 4); // Duplicate key, will overwrite the previous value

 

        for (Map.Entry<String, Integer> entry : map.entrySet()) {

            System.out.println(entry.getKey() + ": " + entry.getValue());

        }

    }

}


2. Iteration and Manipulation of Collections

Iteration

There are several ways to iterate over collections in Java:

  • For-each loop: Suitable for all types of collections.

List<String> list = new ArrayList<>();

list.add("Apple");

list.add("Banana");

list.add("Cherry");

 

for (String fruit : list) {

    System.out.println(fruit);

}

  • Iterator: Provides a way to iterate over elements in a collection and allows the removal of elements during iteration.

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

 

public class IteratorExample {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();

        list.add("Apple");

        list.add("Banana");

        list.add("Cherry");

 

        Iterator<String> iterator = list.iterator();

        while (iterator.hasNext()) {

            String fruit = iterator.next();

            if ("Banana".equals(fruit)) {

                iterator.remove(); // Remove element during iteration

            }

            System.out.println(fruit);

        }

    }

}

  • ListIterator: Allows bidirectional iteration and modification of elements.

import java.util.ArrayList;

import java.util.List;

import java.util.ListIterator;

 

public class ListIteratorExample {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();

        list.add("Apple");

        list.add("Banana");

        list.add("Cherry");

 

        ListIterator<String> listIterator = list.listIterator();

        while (listIterator.hasNext()) {

            String fruit = listIterator.next();

            if ("Banana".equals(fruit)) {

                listIterator.set("Blueberry"); // Modify element

            }

        }

 

        for (String fruit : list) {

            System.out.println(fruit);

        }

    }

}


Manipulation

Common manipulation operations include adding, removing, and updating elements.

  • Adding elements: add() method for lists and sets, put() method for maps.

List<String> list = new ArrayList<>();

list.add("Apple");

list.add("Banana");

 

Set<String> set = new HashSet<>();

set.add("Apple");

set.add("Banana");

 

Map<String, Integer> map = new HashMap<>();

map.put("Apple", 1);

map.put("Banana", 2);

  • Removing elements: remove() method for lists and sets, remove() method for maps.

list.remove("Banana");

 

set.remove("Banana");

 

map.remove("Banana");

  • Updating elements: For lists, use set(). For maps, use put().

list.set(1, "Blueberry"); // Update element at index 1

 

map.put("Apple", 4); // Update value for key "Apple"


3. Generics in Collections

Generics provide a way to define classes, interfaces, and methods with a placeholder for types (parameters) to ensure type safety.

Example of Generics in Collections:

import java.util.ArrayList;

import java.util.List;

 

public class GenericsExample {

    public static void main(String[] args) {

        // Using generics to ensure type safety

        List<String> list = new ArrayList<>();

        list.add("Apple");

        list.add("Banana");

        // list.add(123); // Compile-time error

 

        for (String fruit : list) {

            System.out.println(fruit);

        }

    }

}

Advantages of Generics

  1. Type Safety: Ensures that you can only add the specified type to the collection, reducing runtime errors.

  2. Elimination of Casts: Reduces the need for casting when retrieving elements from a collection.

// Without generics

List list = new ArrayList();

list.add("Apple");

String fruit = (String) list.get(0); // Need to cast

 

// With generics

List<String> genericList = new ArrayList<>();

genericList.add("Apple");

String genericFruit = genericList.get(0); // No cast needed

  1. Enhanced Code Reusability: Allows for the creation of classes, interfaces, and methods that can be reused for different data types.

Generic Methods

Methods can also be generic.

public class GenericMethodExample {

    // Generic method

    public static <T> void printArray(T[] array) {

        for (T element : array) {

            System.out.println(element);

        }

    }

 

    public static void main(String[] args) {

        Integer[] intArray = {1, 2, 3, 4, 5};

        String[] stringArray = {"Apple", "Banana", "Cherry"};

 

        printArray(intArray); // Calling generic method with Integer array

        printArray(stringArray); // Calling generic method with String array

    }

}

Conclusion

The Java Collections Framework provides a comprehensive set of interfaces and classes for handling groups of objects. By understanding and utilizing lists, sets, maps, iteration techniques, and generics, you can write more efficient, type-safe, and maintainable Java Programs.



FAQ

Any Questions?
Look Here.

Related Articles

Abstraction in Java

Binding in Java

Break Statement in Java

Classes & Objects in Java

Comments in Java

Continue Statement in Java

Control Statements in Java

Data Types in Java

Do While-Loop in Java

Encapsulation in Java

Exception Handling in Java

For-Loop In Java

Hello World Program in Java

If-else Statement in Java

Inheritance in Java

Introduction to Java

Java Database Connectivity (JDBC)

Java Development Tools and Frameworks

Java GUI (Graphical User Interface) Programming

Java I/O

Java Vs. C++

Methods and Constructors in Java

Multithreading in Java

Object Oriented Programming in Java

Operators in Java

Polymorphism in Java

Scanner Class in Java

Setting Up Java Environment

Static Keyword in Java

Super Keyword in Java

Switch Statement in Java

This Keyword in Java

Variables in Java

While-Loop in Java