Working with Java Collections: List, Set, Map, and Iterator

Markdown

View as Markdown

The Java Collections Framework provides a set of classes and interfaces that make it easier to store, organize, and manipulate groups of objects efficiently. Instead of working with fixed-size arrays, collections allow applications to manage dynamic data structures that can grow or shrink as needed.

Collections are widely used in real-world applications such as banking systems, e-commerce platforms, inventory management systems, and database-driven applications. In this article, you'll learn how to work with Java's most commonly used collection types, including List, Set, Map, and Iterator.

Learning Objectives

  • Understand the Java Collections Framework.

  • Work with ArrayList and LinkedList.

  • Store unique values using HashSet and TreeSet.

  • Manage key-value pairs using HashMap and TreeMap.

  • Use Iterator to traverse collections.

  • Differentiate between List, Set, and Map.

  • Apply collections effectively in Java applications.

What is the Java Collections Framework?

The Java Collections Framework provides predefined classes and interfaces for storing and managing groups of objects efficiently.

Some commonly used collection types include:

  • List

  • Set

  • Map

  • Queue

  • Iterator

 Benefits of using collections include:

  • Dynamic storage management

  • Faster data manipulation

  • Improved code readability

  • Built-in sorting and searching capabilities

  • Better application scalability

Understanding List

A List stores elements in an ordered sequence and allows duplicate values.

Popular implementations include:

  • ArrayList

  • LinkedList

Lists are commonly used when:

  • The order of elements matters.

  • Duplicate values are allowed.

  • Frequent access to data is required.

ArrayList

ArrayList is one of the most widely used collection classes in Java. It provides dynamic arrays that automatically adjust their size as elements are added or removed.

Example

import java.util.ArrayList;

public class ArrayListExample {

    public static void main(String[] args) {

        ArrayList<String> courses =

                new ArrayList<>();

 

        courses.add("Java");

        courses.add("Python");

        courses.add("MySQL");

        System.out.println(courses);

    }

}

Output

[Java, Python, MySQL]

 

Common ArrayList Methods

Method

Description

add()

Adds an element

remove()

Removes an element

get()

Retrieves an element

size()

Returns the collection size

contains()

Checks if an element exists

clear()

Removes all elements

 Example

ArrayList<String> students =

        new ArrayList<>();

students.add("John");

students.add("David");

System.out.println(students.size());

Output

2

 

LinkedList

LinkedList stores data using linked nodes. It is particularly useful when frequent insertion and deletion operations are required.

Example

import java.util.LinkedList;

public class LinkedListExample {

    public static void main(String[] args) {

        LinkedList<String> cities =

                new LinkedList<>();

        cities.add("Doha");

        cities.add("Dubai");

        cities.add("London");

        System.out.println(cities);

    }

}

Output

[Doha, Dubai, London]

Understanding Set

A Set stores unique values and does not allow duplicate elements.

Popular implementations include:

  • HashSet

  • TreeSet

Sets are commonly used when:

  • Duplicate values are not allowed.

  • Fast searching is required.

  • Unique records must be maintained.

HashSet

HashSet stores unique values in no particular order.

Example

import java.util.HashSet;

public class HashSetExample {

    public static void main(String[] args) {

        HashSet<String> courses =

                new HashSet<>();

        courses.add("Java");

        courses.add("Python");

        courses.add("Java");

        System.out.println(courses);

    }

}

Output

[Java, Python]

Notice that the duplicate value is automatically removed.

TreeSet

TreeSet stores unique elements in sorted order.

Example

import java.util.TreeSet;

public class TreeSetExample {

    public static void main(String[] args) {

        TreeSet<Integer> numbers =

                new TreeSet<>();

        numbers.add(50);

        numbers.add(20);

        numbers.add(10);

        numbers.add(40);

        System.out.println(numbers);

    }

}

Output

[10, 20, 40, 50]

TreeSet automatically sorts its elements in ascending order.

Understanding Map

A Map stores data as key-value pairs.

Popular implementations include:

  • HashMap

  • TreeMap

 Maps are useful when:

  • Values are associated with unique keys.

  • Fast data retrieval is required.

  • Applications manage records such as IDs and names.

HashMap

HashMap stores key-value pairs without maintaining any specific order.

Example

import java.util.HashMap;

public class HashMapExample {

    public static void main(String[] args) {

        HashMap<Integer, String> students =

                new HashMap<>();

        students.put(101, "John");

        students.put(102, "David");

        System.out.println(students);

    }

}

Output

{101=John, 102=David}

TreeMap

TreeMap stores key-value pairs in sorted order based on the key.

Example

import java.util.TreeMap;

public class TreeMapExample {

 

    public static void main(String[] args) {

        TreeMap<Integer,String> employees =

                new TreeMap<>();

        employees.put(105,"Alex");

        employees.put(101,"John");

        employees.put(103,"David");

        System.out.println(employees);

    }

}

Output

{101=John, 103=David, 105=Alex}

Understanding Iterator

An Iterator is used to traverse elements stored inside collections.

It provides methods such as:

  • hasNext()

  • next()

  • remove()

Example

import java.util.ArrayList;

import java.util.Iterator;

public class IteratorExample {

    public static void main(String[] args) {

        ArrayList<String> names =

                new ArrayList<>();

 

        names.add("John");

        names.add("David");

        names.add("Alex");

        Iterator<String> iterator =

                names.iterator();

        while(iterator.hasNext()) {

            System.out.println(

                    iterator.next());

        }

    }

}

Output

John

David

Alex

 

Difference Between List, Set, and Map

Feature

List

Set

Map

Stores Duplicates

Yes

No

Keys Cannot Be Duplicated

Maintains Order

Yes

Depends on Implementation

Depends on Implementation

Stores Key-Value Pairs

No

No

Yes

Allows Null Values

Yes

Depends on Implementation

Yes

Common Implementations

ArrayList, LinkedList

HashSet, TreeSet

HashMap, TreeMap

Choosing the Right Collection

Collection

Best Used For

ArrayList

Frequently accessing ordered data

LinkedList

Frequent insertion and deletion operations

HashSet

Storing unique values

TreeSet

Maintaining sorted unique values

HashMap

Fast key-value storage

TreeMap

Sorted key-value storage

Iterator

Traversing collections safely

 

Real-World Applications

Collections are widely used in:

  • Banking Applications

  • Student Management Systems

  • Inventory Management Systems

  • Payroll Applications

  • E-commerce Platforms

  • Customer Relationship Management Systems

  • Enterprise Software Development

 Examples include:

  • Managing customer records using HashMap

  • Maintaining product categories using TreeSet

  • Storing employee information using ArrayList

  • Processing reports using Iterator

Common Mistakes

Avoid these common errors when working with collections:

  • Using List when duplicate values should not be allowed.

  • Forgetting to import the required collection classes.

  • Assuming that HashSet preserves insertion order.

  • Accessing non-existent keys from a Map.

  • Modifying collections during iteration improperly.

  • Choosing inappropriate collection implementations for the application's requirements.

Practice Exercise

Write Java programs to:

  1. Store student names using an ArrayList.

  2. Display cities using a LinkedList.

  3. Remove duplicate values using a HashSet.

  4. Store and sort numbers using a TreeSet.

  5. Create a HashMap containing employee IDs and names.

  6. Display sorted records using a TreeMap.

  7. Traverse a collection using an Iterator.

  8. Compare the behavior of List, Set, and Map using sample programs.

Was this article helpful?

Still need help?

Contact us