Java Collections: ArrayList, HashMap, and HashSet
Introduction
The Java Collections Framework gives you ready-made data structures for working with groups of objects. This tutorial introduces the three you'll use most: ArrayList for ordered lists, HashMap for key-value lookups, and HashSet for unique values.
Prerequisites
- JDK installed
- Understanding of classes, objects, and generics syntax like List<String>
Step-by-Step Guide
Step 1: Use ArrayList for ordered lists
An ArrayList grows automatically and keeps items in insertion order. Declare it using the List interface. The examples below belong inside a method such as main.
import java.util.ArrayList;
import java.util.List;
List<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
System.out.println(languages.get(0)); // Java
System.out.println(languages.size()); // 2Step 2: Use HashMap for key-value pairs
A HashMap stores values by key and looks them up quickly.
import java.util.HashMap;
import java.util.Map;
Map<String, Integer> scores = new HashMap<>();
scores.put("Ava", 92);
scores.put("Ben", 85);
System.out.println(scores.get("Ava")); // 92Step 3: Use HashSet for unique values
A HashSet ignores duplicates, which makes it ideal for removing repeats or checking membership.
import java.util.HashSet;
import java.util.Set;
Set<String> unique = new HashSet<>();
unique.add("java");
unique.add("java");
System.out.println(unique.size()); // 1Step 4: Loop through collections
Use the enhanced for loop for lists and sets, and entrySet() to read keys and values from a map together.
for (String language : languages) {
System.out.println(language);
}
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}FAQs
- What is the difference between an array and an ArrayList?
- An array has a fixed size. An ArrayList resizes automatically and offers helper methods, but it stores objects rather than primitives directly.
- Does HashSet keep items in order?
- No. HashSet doesn't guarantee order. Use LinkedHashSet to keep insertion order or TreeSet to keep items sorted.
Summary
Pick ArrayList when order matters, HashMap when you look things up by key, and HashSet when you need uniqueness. Declare variables using the interface type (List, Map, Set) so you can swap implementations later.
Comments
Log in or create a free account to join the discussion.