Java · Lesson 8 of 9
Collections & generics
List, Set, Map, generics and a first look at streams.
The Collections Framework provides ready-made data structures:
List(ArrayList) — ordered, allows duplicates, index access.Set(HashSet,TreeSet) — unique elements.Map(HashMap,TreeMap) — key → value lookups.Queue/Deque(ArrayDeque) — FIFO/LIFO processing.
Generics (List<String>) tell the compiler what type a collection holds, catching mistakes at compile time.
Streams (Java 8+) process collections declaratively: filter, map, sorted, collect.
Example program
Run with JDK 17+: java Main.javaimport java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<String> skills = new ArrayList<>(List.of("Java", "SQL", "Spring", "SQL", "Git"));
Set<String> unique = new TreeSet<>(skills);
System.out.println(unique);
Map<String, Integer> openings = new HashMap<>();
openings.put("Kochi", 12);
openings.put("Thiruvananthapuram", 9);
openings.merge("Kochi", 3, Integer::sum); // add 3 more
System.out.println("Kochi openings: " + openings.get("Kochi"));
System.out.println(openings.getOrDefault("Kannur", 0));
List<String> longSkills = skills.stream()
.distinct()
.filter(s -> s.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(longSkills);
}
}
Output
[Git, Java, SQL, Spring]
Kochi openings: 15
0
[JAVA, SPRING]
Save the code as Main.java and run java Main.java (JDK 11+ runs single files directly). Names and figures are fictional.
Key points
- List = ordered; Set = unique; Map = key → value.
- Generics give compile-time type safety.
- Streams express filter/map/collect pipelines.
Quick check
Which collection rejects duplicate elements?
Sets store each element at most once.
Practice task
Count how many times each word appears in a List<String> using a HashMap and merge().
Interview corner
How does HashMap work internally?
It hashes the key to pick a bucket in an array; collisions are stored in a linked list that becomes a balanced tree when large (Java 8+). get/put are O(1) on average.
ArrayList vs LinkedList?
ArrayList gives fast random access and is usually faster overall. LinkedList allows cheap inserts/removals at known positions but slow index access.
Further reading
Official documentation, linked for deeper study. These are outside sites; this lesson's text is our own.
Original lesson written by the InfoparkDaily team · © 2026 InfoparkDaily · Free to learn — no paid course or subscription.