Generics and Lambda Expressions
Lesson 19 of 20Write code once for every type: angle-bracket generics checked at compile time, lambdas that shrink boilerplate to one line.
Angle brackets and arrows
Generics let one class work for every type — safely, at compile time. Lambdas let you pass behavior itself, with no ceremony.
T is a placeholder
List<String> fills the T slot with String; the compiler then rejects every wrong-type attempt.
No more casts
get(0) on a List<String> returns a String — no (String) cast, no ClassCastException risk.
Lambda = tiny function
n -> System.out.println(n) is a method compressed to its input and its body.
Where lambdas shine
forEach, sort and filters accept them — behavior travels like data.
Java 5
Generics arrive: collections finally know what they hold.
Java 8
Lambda expressions and Streams change how behavior is passed around.
Everywhere
List<T>, Map<K,V> and lambdas are the everyday Java style.
What happens to generics
Checked hard at compile time — then quietly erased before runtime.
A typed list meets a lambda
The <String> promise guards every add; the lambda runs once per element, in list order.
1import java.util.ArrayList;2import java.util.List;34public class TeamDemo {5public static void main(String[] args) {6List<String> team = new ArrayList<>();7team.add("Ada");8team.add("Bo");9team.forEach(n -> System.out.println("Hi " + n));10}11}
main begins.
Lambda per element
How many times does the arrow fire, and with what?
1import java.util.ArrayList;23public class GreetDemo {4public static void main(String[] args) {5ArrayList<String> team = new ArrayList<>();6team.add("Ada");7team.add("Bo");8team.forEach(n -> System.out.println("=> " + n));9}10}
Hint: The lambda runs once per element, in list order — n is "Ada" first, then "Bo", each getting the "=> " prefix.
Modern Java shorthand
Click a term, then click its meaning.
Key takeaways
Generics move type errors from runtime to compile time — that is the whole win.
List<String> means get() returns String: no casts, no surprises.
Type arguments are erased after checking; runtime bytecode is unchanged.
A lambda is a method shrunk to parameters and body: n -> ...
APIs that take lambdas (forEach, sort, Streams) let you pass behavior like data.