Skip to content

๐Ÿ“š Java Collections Framework โ€“ List, Set, Map Explained

๐Ÿ”– Introduction

As your Java application grows, handling large sets of data becomes common. The Collections Framework provides powerful classes to store, manipulate, and organize groups of objects.

In this lesson, weโ€™ll explore the three most commonly used interfaces:

  • List
  • Set
  • Map

๐Ÿงบ What is the Collections Framework?

The Collections Framework is a set of interfaces and classes in java.util that help you work with groups of objects more easily.


๐Ÿ“‹ 1. List โ€“ Ordered & Duplicates Allowed

A List is an ordered collection that allows duplicates.

โœ… Common Implementations:

  • ArrayList (most used)
  • LinkedList

๐Ÿ”น Example:

import java.util.*;

public class ListExample {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();

        names.add("Alice");
        names.add("Bob");
        names.add("Alice");  // duplicate allowed

        System.out.println(names);  // [Alice, Bob, Alice]
    }
}

๐Ÿ”ข 2. Set โ€“ Unordered & No Duplicates

A Set is a collection that does not allow duplicates.

โœ… Common Implementations:

  • HashSet (unordered)
  • LinkedHashSet (keeps insertion order)
  • TreeSet (sorted)

๐Ÿ”น Example:

import java.util.*;

public class SetExample {
    public static void main(String[] args) {
        Set<String> fruits = new HashSet<>();

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Apple");  // duplicate ignored

        System.out.println(fruits);  // [Apple, Banana]
    }
}

๐Ÿ”‘ 3. Map โ€“ Key-Value Pairs

A Map stores key-value pairs, like a dictionary.

โœ… Common Implementations:

  • HashMap (unordered)
  • LinkedHashMap (insertion order)
  • TreeMap (sorted keys)

๐Ÿ”น Example:

import java.util.*;

public class MapExample {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();

        scores.put("Alice", 90);
        scores.put("Bob", 85);
        scores.put("Alice", 95);  // overwrites previous value

        System.out.println(scores);  // {Alice=95, Bob=85}
    }
}

๐Ÿ”ง Useful Methods:

scores.get("Alice");
scores.containsKey("Bob");
scores.remove("Alice");
scores.keySet();     // returns all keys
scores.values();     // returns all values

๐Ÿง  When to Use What?

CollectionAllows DuplicatesMaintains OrderKey-Value Storage
Listโœ…โœ…โŒ
SetโŒโŒ (except LinkedHashSet)โŒ
Mapโœ… (keys must be unique)N/Aโœ…

๐Ÿงช Mini Challenge

List<Integer> nums = new ArrayList<>();
nums.add(10);
nums.add(20);
nums.add(10);

Set<Integer> uniqueNums = new HashSet<>(nums);
System.out.println("Unique: " + uniqueNums);

โœ… What You Learned

  • The core Java collections: List, Set, and Map
  • How to choose the right one based on your needs
  • Real-world examples and key operations

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *