⚡0 XP🔥0

Lambdas and the Stream API

Lesson 14 of 15 ⏱ 6 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs Java

Write lambdas and method references, use built-in functional interfaces (Predicate, Function, Consumer, Supplier), and process collections with streams - filter, map, reduce, sorted, collect, groupingBy and Optional.

Java 8 added functional programming features: lambdas (short anonymous functions) and the Stream API (a pipeline for processing collections). Modern Java code - and almost every Spring Boot project - uses them everywhere.

Lambda expressions#

A lambda is a function without a name: (parameters) -> expression or (parameters) -> { statements }.

▶ Try it YourselfJava
Ctrl + Enter to run
Output
[Om, Rohan, Aditi, Kabir, Meera]
[Aditi, Kabir, Meera, Om, Rohan]
AKMOR
[Aditi, Kabir, Meera, Rohan]

A lambda can be used wherever a functional interface (an interface with one abstract method) is expected - Comparator, Runnable, and the ones in java.util.function.

हिंदी में समझें

Lambda एक छोटा, बिना नाम का function है: x -> x * 2 का मतलब "x लो, x×2 लौटाओ"। पहले इसी काम के लिए पूरी anonymous class लिखनी पड़ती थी। Lambda से code छोटा और पढ़ने में आसान हो जाता है।

Built-in functional interfaces#

Interface Method Shape Example
Predicate<T> test T → boolean m -> m >= 40
Function<T, R> apply T → R s -> s.length()
Consumer<T> accept T → nothing s -> System.out.println(s)
Supplier<T> get nothing → T () -> new ArrayList<>()
BinaryOperator<T> apply (T, T) → T (a, b) -> a + b
▶ Try it YourselfJava
Ctrl + Enter to run
Output
false true
1180.0
JAVA STREAMS!
Namaste
42
true false

Method references#

When a lambda just calls an existing method, a method reference is even shorter:

Lambda Method reference
s -> s.length() String::length
x -> System.out.println(x) System.out::println
s -> Integer.parseInt(s) Integer::parseInt
() -> new ArrayList<>() ArrayList::new

Streams: filter, map, reduce#

A stream is a sequence of elements you process in a pipeline: source → intermediate operations → terminal operation.

▶ Try it YourselfJava
Ctrl + Enter to run
Output
[16, 64, 256, 1764]
sum = 119
count > 10: 5
max: 42
sorted desc: [42, 23, 16, 15, 11, 8, 4]
any > 40? true
all positive? true
  • Intermediate operations (filter, map, sorted, distinct, limit, skip) return a new stream and are lazy.
  • Terminal operations (toList, collect, forEach, count, reduce, sum, anyMatch) run the pipeline and produce a result.
  • Streams do not change the original collection.

Numeric streams and statistics#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
min 45, max 92, avg 70.66666666666667
sum of 1..100 = 5050
1, 4, 9, 16, 25

Streams of objects: collect, groupingBy, Optional#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
Above 1 lakh: [Pradeep, Rajesh, Ritu, Sunita]
Count by dept: {CSE=3, ECE=2, MBA=1}
CSE average 111667
ECE average 105000
MBA average 150000
Top earner: Ritu
Civil staff present? false -> nobody
Rajesh,Sunita,Amit,Pradeep,Kiran,Ritu

Optional<T> is a box that may or may not contain a value. Methods like orElse, map and isPresent replace error-prone null checks.

Tip

Streams make data processing read like a sentence: "from staff, filter salary > 1 lakh, map to name, sort, collect". They are ideal for transforming and summarising data; use a plain loop when you need complex control flow or to modify things in place.

Summary#

  • Lambdas ((a, b) -> a + b) implement functional interfaces; method references (String::length) are shorter still.
  • Predicate, Function, Consumer, Supplier cover most needs.
  • Stream pipeline: source → filter/map/sorted/limit (lazy) → toList/collect/count/reduce (terminal).
  • Collectors.groupingBy, counting, averagingDouble, joining summarise data; Optional avoids nulls.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Stream statistics

For the list of marks in the starter, use streams to print:

Passed (>= 40): [72, 91, 66, 88, 54]
Average of passed: 74.2
Top 3: [91, 88, 72]
Expected output:
Passed (>= 40): [72, 91, 66, 88, 54]
Average of passed: 74.2
Top 3: [91, 88, 72]
2

Group students by city

Using Collectors.groupingBy with a TreeMap, print the names of students per city (alphabetical by city), e.g. Bhopal=[Aarav, Yash].

Expected output:
Bhopal=[Aarav, Yash]
Gwalior=[Om]
Indore=[Diya, Neha]
Jabalpur=[Kabir]

Quick Quiz

Q1.

What does x -> x * 2 represent?

Q2.

Which functional interface takes a value and returns a boolean?

Q3.

When does a stream pipeline actually run?

Q4.

List.of(3, 1, 2).stream().map(x -> x * x).toList() gives...

Q5.

What is String::length?