Download the complete example ZIP
Choose a Java collection by the question your program needs to answer. A visit log needs to retain repeated entries in order. A unique visitor list needs to discard duplicate names. A frequency report needs to associate each name with a count. Those are three different requirements, even when they start from the same input.
This runnable console example uses ArrayList, HashSet and HashMap to process three fictional visits. It also demonstrates a common integer-list mistake: removing the value one is different from removing the item at index one. The complete program has no external libraries and includes explicit checks that run without enabling Java assertions.
Compile and run with JDK 17 or later
Save the source as CollectionsDemo.java. The filename must match the public class name. In the same directory run javac CollectionsDemo.java, followed by java CollectionsDemo. A Java runtime alone is not enough to compile the file; the JDK supplies javac.
CollectionsDemo.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
public class CollectionsDemo {
public static void main(String[] args) {
List<String> visits = new ArrayList<>(List.of("Mira", "Asha", "Mira"));
Set<String> uniqueVisitors = new HashSet<>(visits);
Map<String, Integer> counts = new HashMap<>();
for (String name : visits) {
counts.merge(name, 1, Integer::sum);
}
System.out.println("Visits: " + visits);
// HashSet/HashMap have no promised iteration order; sort only for display.
System.out.println("Unique: " + new TreeSet<>(uniqueVisitors));
System.out.println("Counts: " + new TreeMap<>(counts));
System.out.println("Missing visitor count: " + counts.getOrDefault("Dev", 0));
List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3));
numbers.remove(Integer.valueOf(1));
System.out.println("Remove value 1: " + numbers);
numbers.remove(1);
System.out.println("Then remove index 1: " + numbers);
require(visits.size() == 3, "List should retain duplicate visits.");
require(uniqueVisitors.size() == 2, "Set should contain two unique names.");
require(counts.get("Mira") == 2, "Map should count both Mira visits.");
require(numbers.equals(List.of(2)), "Removal overload example failed.");
System.out.println("Checks passed.");
}
private static void require(boolean condition, String message) {
if (!condition) throw new IllegalStateException(message);
}
}
Read the output
Visits: [Mira, Asha, Mira]
Unique: [Asha, Mira]
Counts: {Asha=1, Mira=2}
Missing visitor count: 0
Remove value 1: [2, 3]
Then remove index 1: [2]
Checks passed.
The program was compiled and run with Microsoft OpenJDK 17.0.11. Its output matched the block above, and all four explicit checks passed. The names represent invented sample data. This is a behavior demonstration, not a performance comparison between collection implementations.
Use a list for ordered occurrences
The ArrayList retains all three visits, including Mira's second visit. Replacing it with a set would lose the fact that someone appeared twice. A list also lets you access an item by position. Position can be useful for a small display, but it is not necessarily a stable identity after insertions and removals.
The initial names come from List.of, and the constructor copies them into a mutable ArrayList. The later integer example does the same so that removal is permitted. Keep the distinction between the source list and the mutable copy clear when adapting the program.
Use a set for membership
The HashSet receives all visits but keeps only the two distinct names. That suits a question such as whether Asha visited at least once. It cannot tell you how many times she visited. The example wraps the set in a TreeSet only when printing, giving a stable alphabetical display. It does not rely on HashSet iteration order.
Use a map for values attached to keys
The HashMap stores a count for each name. The merge operation creates the first count or adds one to an existing count. Reading an unknown name with getOrDefault produces the deliberate fallback zero. Printing through a TreeMap makes the displayed order predictable; the counting map itself is still a HashMap.
Real applications should decide what identifies a person. Two different users can share a display name, so this demonstration's string key is not a suitable production account identity. Use an application-defined identifier when names are not unique. Check ArrayList, HashSet and HashMap in the Java API documentation when changing the behavior.
Avoid the remove overload trap
For a List of Integer, passing the primitive integer one selects removal by index. Passing Integer.valueOf(1) selects removal by object value. The example first removes the value one from [1, 2, 3], leaving [2, 3]. Removing index one after that removes the second remaining element, leaving [2].
Try changing the input so that a value is absent or a requested index is outside the list, and handle each case deliberately. A useful next extension is to read names from a file, preserve the original visit list and generate a separate frequency report. Keep the sample's explicit checks while modifying the input path so collection semantics remain visible rather than hidden behind file-reading code.
Comments (0)
Join the discussion