Java Course

Java Collections: ArrayList, HashMap, and More

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

What are Collections?

The Java Collections Framework provides ready-to-use data structures. The main interfaces are List, Set, and Map.

ArrayList

import java.util.ArrayList;

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

System.out.println(fruits.get(1));   // "Banana"
System.out.println(fruits.size());   // 3
fruits.remove("Banana");
System.out.println(fruits);          // [Apple, Cherry]

// Iterate
for (String fruit : fruits) {
    System.out.println(fruit);
}

HashMap

import java.util.HashMap;

HashMap scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
scores.put("Charlie", 91);

System.out.println(scores.get("Alice")); // 95
System.out.println(scores.containsKey("Bob")); // true
scores.remove("Bob");

// Iterate over entries
for (var entry : scores.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

HashSet

import java.util.HashSet;

HashSet set = new HashSet<>();
set.add(1); set.add(2); set.add(3); set.add(2);
System.out.println(set);       // [1, 2, 3] — no duplicates
System.out.println(set.contains(2)); // true

Choosing the Right Collection

NeedUse
Ordered list, allow duplicatesArrayList
Fast insert/delete at both endsLinkedList / ArrayDeque
No duplicates, fast lookupHashSet
Sorted unique elementsTreeSet
Key-value pairsHashMap
Sorted key-value pairsTreeMap

Sorting Collections

import java.util.Collections;
import java.util.List;

List nums = new ArrayList<>(List.of(5, 2, 8, 1, 9));
Collections.sort(nums);
System.out.println(nums); // [1, 2, 5, 8, 9]

// With lambda (Java 8+)
nums.sort((a, b) -> b - a); // descending
System.out.println(nums); // [9, 8, 5, 2, 1]