Today you will learn:
ArrayList and LinkedListHashMap and HashSetfor loopsBy the end, you will be able to use Java collections effectively to store, manipulate, and retrieve data.
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");
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
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());
}
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);
}
ArrayList numbers = new ArrayList<>(Arrays.asList(5,3,8,1));
Collections.sort(numbers);
for(int n : numbers) {
System.out.println(n);
}
Store a list of numbers, remove duplicates, and sort them ascending.
Steps:
HashSet to remove duplicatesExample:
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]
}
}