Java — Collections
ArrayList
import java.util.*;
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println(names.get(0)); // Alice
System.out.println(names.size()); // 3
names.remove("Bob");
names.set(0, "Alicia");
LinkedList
LinkedList<Integer> nums = new LinkedList<>();
nums.addFirst(1);
nums.addLast(3);
nums.add(1, 2); // Add at index
System.out.println(nums.getFirst()); // 1
System.out.println(nums.getLast()); // 3
HashSet
HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate ignored
System.out.println(set.size()); // 2
System.out.println(set.contains("Banana")); // true
TreeSet
TreeSet<Integer> sorted = new TreeSet<>();
sorted.add(5);
sorted.add(2);
sorted.add(8);
sorted.add(1);
System.out.println(sorted); // [1, 2, 5, 8]
System.out.println(sorted.first()); // 1
System.out.println(sorted.last()); // 8
HashMap
HashMap<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
System.out.println(ages.get("Alice")); // 30
System.out.println(ages.containsKey("Charlie")); // false
// Iterate
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Collections utilities
import java.util.*;
List<Integer> nums = Arrays.asList(5, 2, 8, 1, 9);
Collections.sort(nums);
Collections.reverse(nums);
Collections.shuffle(nums);
int max = Collections.max(nums);
int min = Collections.min(nums);
Iterating
List<String> names = List.of("Alice", "Bob", "Charlie");
// Enhanced for loop
for (String name : names) {
System.out.println(name);
}
// forEach
names.forEach(System.out::println);
// Iterator
Iterator<String> it = names.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Mini Practice
Write Java code that:
- Creates an ArrayList and manipulates it
- Uses a HashMap to count word frequencies
- Uses Collections.sort with a comparator
- Iterates a map with entrySet
Up Next
In the next lesson, you'll learn about Generics — type-safe reusable code.
Related Topics
Frequently Asked Questions about Collections
What is Collections in Java?
Collections is a fundamental concept in Java. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Collections?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Collections.
Why is Collections important in Java?
Collections is essential for Java development. Understanding this concept will help you write better code and solve real-world problems more effectively.