Intermediate Java Day 6: Collections Framework

Goal of this Day

Today you will learn:

By the end, you will be able to use Java collections effectively to store, manipulate, and retrieve data.

Step 1: ArrayList & LinkedList

ArrayList is a resizable array, LinkedList is a doubly linked list.


import java.util.ArrayList;
import java.util.LinkedList;

ArrayList fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");

LinkedList animals = new LinkedList<>();
animals.add("Dog");
animals.add("Cat");

Step 2: HashMap & HashSet

HashMap stores key-value pairs. HashSet stores unique elements.


import java.util.HashMap;
import java.util.HashSet;

HashMap ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);

HashSet numbers = new HashSet<>();
numbers.add(5);
numbers.add(3);
numbers.add(5); // duplicates are ignored

Step 3: Iterators & Enhanced Loops

You can iterate through collections using for-each or iterators.


for(int n : numbers) {
    System.out.println(n);
}

import java.util.Iterator;
Iterator it = numbers.iterator();
while(it.hasNext()) {
    System.out.println(it.next());
}

Step 4: Sorting & Searching

You can sort lists and search for elements.


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

ArrayList numbers = new ArrayList<>(Arrays.asList(5,3,8,1));
Collections.sort(numbers); // ascending order

for(int n : numbers) {
    System.out.println(n);
}

Practice


ArrayList numbers = new ArrayList<>(Arrays.asList(5,3,8,1));
Collections.sort(numbers);
for(int n : numbers) {
    System.out.println(n);
}

Exercise

Store a list of numbers, remove duplicates, and sort them ascending.

Steps:

Example:


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;

public class UniqueSortedList {
    public static void main(String[] args) {
        ArrayList numbers = new ArrayList<>(Arrays.asList(5, 3, 8, 1, 3, 5));

        // Remove duplicates
        HashSet uniqueNumbers = new HashSet<>(numbers);

        // Convert back to list
        ArrayList sortedNumbers = new ArrayList<>(uniqueNumbers);

        // Sort
        Collections.sort(sortedNumbers);

        System.out.println(sortedNumbers); // [1, 3, 5, 8]
    }
}