Collections
ArrayList, HashMap and HashSet: the classes you will use most.
Collections grow as needed, unlike arrays. They hold objects, so use Integer rather than int in the angle brackets.
Java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> skills = new ArrayList<>();
skills.add("Java");
skills.add("SQL");
skills.remove("SQL");
System.out.println(skills + " " + skills.size());
Map<String, Integer> counts = new TreeMap<>();
for (char c : "banana".toCharArray()) {
counts.merge(String.valueOf(c), 1, Integer::sum);
}
System.out.println(counts);
Set<Integer> unique = new TreeSet<>(List.of(3, 1, 3, 2));
System.out.println(unique);
}
}Output
[Java] 1
{a=3, b=1, n=2}
[1, 2, 3]| Class | Use it when |
|---|---|
ArrayList | You want an ordered list with fast access by index |
HashMap | You look values up by key. Order is not guaranteed |
HashSet | You need unique items and fast contains() |
TreeMap / TreeSet | You want them kept sorted |
ArrayDeque | You need a stack or queue |
Streams
Java
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);
int total = nums.stream().filter(n -> n % 2 == 0).mapToInt(n -> n * n).sum();
System.out.println(total);
}
}Output
56