LearnFrenzy
Sign in Take a free test

Java Programming · Topic 22 of 28

Streams API

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Streams API · Study material

The Stream API (Java 8+, package java.util.stream) lets you process collections of data declaratively: you describe what you want – "orders from Pune above ₹1,000, customer names in capitals" – as a pipeline of operations, and the library works out how. A stream is not a data structure; it is a lazy sequence of elements flowing from a source (a list, an array, a range, a file) through intermediate operations (filter, map, sorted, distinct, flatMap …) to one terminal operation (toList, collect, count, reduce, forEach …) that produces the result. Combined with lambdas, streams replace most hand-written loops with readable, composable code, and Collectors makes grouping and aggregating – SQL-style reports – a few lines long. Streams are tested heavily in Java interviews, especially laziness, map vs flatMap, groupingBy and the "stream has already been operated upon" trap. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – compiled and run on Java 21.

On this page

  • Stream pipelines: source, intermediate and terminal operations
  • Creating streams
  • filter, map, flatMap, distinct, sorted, limit, skip, takeWhile, dropWhile
  • Terminal operations, reduce and Optional results
  • Primitive streams and statistics
  • Collectors, laziness, single use and parallel streams

A stream pipeline

import java.util.ArrayList;
import java.util.List;

record Order(String customer, String city, double amount) { }

public class Main {
    public static void main(String[] args) {
        List<Order> orders = List.of(new Order("Asha", "Pune", 1250), new Order("Ravi", "Delhi", 320),
            new Order("Meena", "Pune", 4100), new Order("John", "Mumbai", 980), new Order("Zoya", "Pune", 760));

        // Imperative: HOW to do it, step by step
        List<String> loop = new ArrayList<>();
        for (Order o : orders) if (o.city().equals("Pune") && o.amount() > 1000) loop.add(o.customer().toUpperCase());

        // Declarative stream: WHAT you want – source → intermediate operations → terminal operation
        List<String> stream = orders.stream()                       // source
            .filter(o -> o.city().equals("Pune"))                   // keep matching elements
            .filter(o -> o.amount() > 1000)
            .map(o -> o.customer().toUpperCase())                   // transform each element
            .toList();                                              // terminal: produce the result (Java 16+)

        double puneTotal = orders.stream().filter(o -> o.city().equals("Pune")).mapToDouble(Order::amount).sum();
        System.out.println(loop + " " + stream + " " + puneTotal);
    }
}

Output

[ASHA, MEENA] [ASHA, MEENA] 6110.0
PartExamplesReturns
sourcelist.stream(), Stream.of, Arrays.stream, IntStream.rangea stream
intermediate (lazy)filter, map, flatMap, distinct, sorted, peek, limit, skipa new stream
terminal (eager)toList, collect, forEach, count, reduce, min, anyMatch, findFirsta result or a side effect

Creating streams

import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        System.out.println(List.of(3, 1, 2).stream().count());                              // from a collection
        System.out.println(Stream.of("a", "b", "c").toList());                              // from values
        System.out.println(Arrays.stream(new int[]{4, 5, 6}).sum());                        // from an array
        System.out.println(IntStream.range(1, 5).boxed().toList() + " " + IntStream.rangeClosed(1, 5).sum());
        System.out.println(Stream.iterate(1, n -> n * 2).limit(8).toList());               // infinite → limit
        System.out.println(Stream.iterate(10, n -> n > 0, n -> n - 3).toList());            // iterate with a stop condition
        System.out.println(Stream.generate(() -> "ab").limit(3).reduce("", String::concat));
        System.out.println("hello".chars().filter(c -> c == 'l').count() + " " + "a,b,,c".split(",").length);
        System.out.println(Stream.of("x").count() + Stream.empty().count());
    }
}

Output

3
[a, b, c]
15
[1, 2, 3, 4] 15
[1, 2, 4, 8, 16, 32, 64, 128]
[10, 7, 4, 1]
ababab
2 4
1

Intermediate operations

map turns each element into exactly one new element; flatMap turns each element into a stream and joins them all into one flat stream. distinct uses equals, sorted needs Comparable elements or a Comparator, and takeWhile/dropWhile (Java 9) stop or start at the first element that fails the condition.

import java.util.Comparator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> nums = List.of(5, 3, 8, 3, 9, 1, 8, 6, 2, 7);

        System.out.println(nums.stream().distinct().toList());                          // remove duplicates (keeps first)
        System.out.println(nums.stream().sorted().toList());                            // natural order
        System.out.println(nums.stream().sorted(Comparator.reverseOrder()).limit(3).toList());   // top 3
        System.out.println(nums.stream().skip(7).toList());                             // drop the first 7
        System.out.println(nums.stream().takeWhile(n -> n != 1).toList());              // take until the condition fails
        System.out.println(nums.stream().dropWhile(n -> n != 1).toList());              // drop until the condition fails

        List<List<String>> teams = List.of(List.of("Asha", "Ravi"), List.of("Meena"), List.of("John", "Zoya", "Neha"));
        System.out.println(teams.stream().flatMap(List::stream).map(String::length).toList());   // flatten, then map
        System.out.println(List.of("a-b", "c", "d-e-f").stream().flatMap(s -> List.of(s.split("-")).stream()).toList());
    }
}

Output

[5, 3, 8, 9, 1, 6, 2, 7]
[1, 2, 3, 3, 5, 6, 7, 8, 8, 9]
[9, 8, 8]
[6, 2, 7]
[5, 3, 8, 3, 9]
[1, 8, 6, 2, 7]
[4, 4, 5, 4, 4, 4]
[a, b, c, d, e, f]

Terminal operations

A terminal operation runs the pipeline and ends the stream. Operations that might have no answer – min, max, findFirst, reduce without an identity – return an Optional. anyMatch, allMatch, noneMatch, findFirst and limit are short-circuiting: they stop as soon as the answer is known.

import java.util.List;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        List<String> words = List.of("stream", "lambda", "map", "filter", "reduce", "java");

        long longOnes = words.stream().filter(w -> w.length() > 4).count();
        Optional<String> shortest = words.stream().min((a, b) -> a.length() - b.length());
        Optional<String> firstJ = words.stream().filter(w -> w.startsWith("j")).findFirst();
        boolean any = words.stream().anyMatch(w -> w.contains("x"));
        boolean all = words.stream().allMatch(w -> w.length() >= 3);
        boolean none = words.stream().noneMatch(String::isEmpty);
        int totalChars = words.stream().map(String::length).reduce(0, Integer::sum);      // identity + accumulator
        Optional<String> longest = words.stream().reduce((a, b) -> a.length() >= b.length() ? a : b);

        System.out.println(longOnes + " " + shortest.get() + " " + firstJ.orElse("-") + " " + any + " " + all + " " + none);
        System.out.println(totalChars + " " + longest.orElseThrow());
        words.stream().filter(w -> w.length() == 6).forEach(w -> System.out.print(w.charAt(0)));
        System.out.println();
    }
}

Output

4 map java false true true
31 stream
slfr

Primitive streams

IntStream, LongStream and DoubleStream avoid boxing and add numeric operations: sum, average, max, summaryStatistics, range. Convert with mapToInt, mapToObj and boxed.

import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.IntStream;

record Student(String name, int marks) { }

public class Main {
    public static void main(String[] args) {
        List<Student> students = List.of(new Student("Asha", 91), new Student("Ravi", 67), new Student("Meena", 84), new Student("John", 45));

        int total = students.stream().mapToInt(Student::marks).sum();          // Stream<Student> → IntStream
        double avg = students.stream().mapToInt(Student::marks).average().orElse(0);
        int max = students.stream().mapToInt(Student::marks).max().getAsInt();
        IntSummaryStatistics stats = students.stream().mapToInt(Student::marks).summaryStatistics();

        System.out.println(total + " " + avg + " " + max);
        System.out.println(stats.getMin() + " " + stats.getMax() + " " + stats.getAverage() + " " + stats.getCount());
        System.out.println(IntStream.rangeClosed(1, 5).map(i -> i * i).boxed().toList() + " " + IntStream.of(3, 1, 2).sorted().mapToObj(i -> "#" + i).toList());
        System.out.println(IntStream.rangeClosed(1, 10).filter(i -> i % 3 == 0).average().getAsDouble() + " " + IntStream.empty().max().isPresent());
    }
}

Output

287 71.75 91
45 91 71.75 4
[1, 4, 9, 16, 25] [#1, #2, #3]
6.0 false

Collectors

collect(Collectors.…) builds a result: a list, a set, a string with joining, a map with toMap, or a grouped report with groupingBy and partitioningBy plus a downstream collector such as counting, summingInt, averagingDouble or mapping. Pass TreeMap::new when you need sorted keys.

import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

record Emp(String name, String dept, double salary, int age) { }

public class Main {
    public static void main(String[] args) {
        List<Emp> staff = List.of(new Emp("Asha", "IT", 90000, 29), new Emp("Ravi", "HR", 50000, 41), new Emp("Meena", "IT", 95000, 35),
                                  new Emp("John", "Sales", 60000, 26), new Emp("Zoya", "HR", 55000, 31), new Emp("Neha", "IT", 70000, 24));

        String names = staff.stream().map(Emp::name).collect(Collectors.joining(", ", "[", "]"));
        Map<String, Long> countByDept = staff.stream().collect(Collectors.groupingBy(Emp::dept, TreeMap::new, Collectors.counting()));
        Map<String, Double> avgSalary = staff.stream().collect(Collectors.groupingBy(Emp::dept, TreeMap::new, Collectors.averagingDouble(Emp::salary)));
        Map<String, List<String>> namesByDept = staff.stream().collect(Collectors.groupingBy(Emp::dept, TreeMap::new, Collectors.mapping(Emp::name, Collectors.toList())));
        Map<Boolean, List<String>> over30 = staff.stream().collect(Collectors.partitioningBy(e -> e.age() > 30, Collectors.mapping(Emp::name, Collectors.toList())));
        Map<String, Double> salaryOf = staff.stream().collect(Collectors.toMap(Emp::name, Emp::salary, (a, b) -> a, TreeMap::new));

        System.out.println(names);
        System.out.println(countByDept + " " + avgSalary);
        System.out.println(namesByDept);
        System.out.println(over30);
        System.out.println(salaryOf.get("Zoya") + " " + salaryOf.keySet());
    }
}

Output

[Asha, Ravi, Meena, John, Zoya, Neha]
{HR=2, IT=3, Sales=1} {HR=52500.0, IT=85000.0, Sales=60000.0}
{HR=[Ravi, Zoya], IT=[Asha, Meena, Neha], Sales=[John]}
{false=[Asha, John, Neha], true=[Ravi, Meena, Zoya]}
55000.0 [Asha, John, Meena, Neha, Ravi, Zoya]

Laziness and single use

Nothing happens until the terminal operation; then each element travels through the whole pipeline before the next one starts, which is what makes short-circuiting and infinite streams possible. A stream can be consumed only once – create a new one (or keep the source collection) to process the data again.

import java.util.List;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        // Intermediate operations are LAZY: nothing runs until a terminal operation is called
        Stream<String> s = List.of("one", "two", "three", "four").stream()
            .peek(w -> System.out.print("[peek " + w + "] "))
            .filter(w -> w.length() > 3);
        System.out.println("pipeline built, nothing printed yet");

        // Elements flow one at a time; findFirst short-circuits after the first match
        System.out.println(s.findFirst().orElse("none"));

        // A stream can be consumed only ONCE
        try {
            s.count();
        } catch (IllegalStateException e) {
            System.out.println("IllegalStateException: " + e.getMessage());
        }

        // Even an infinite stream is fine when a short-circuiting operation ends it
        System.out.println(Stream.iterate(1, n -> n + 1).filter(n -> n % 7 == 0).map(n -> n * n).limit(3).toList());
    }
}

Output

pipeline built, nothing printed yet
[peek one] [peek two] [peek three] three
IllegalStateException: stream has already been operated upon or closed
[49, 196, 441]

Common mistakes

  • Reusing a stream after a terminal operation – IllegalStateException.
  • Forgetting the terminal operation – the pipeline never runs.
  • Side effects in map/filter or adding to an outside list in forEach – collect instead.
  • Calling get() on an empty Optional – use orElse, orElseThrow or ifPresent.
  • toMap with duplicate keys without a merge function – IllegalStateException.
  • Modifying the result of toList() – it is unmodifiable.
  • Using parallel streams on small data or with shared mutable state.
  • Infinite streams without limit or another short-circuiting operation.

Key points to remember

  • Stream = source → intermediate operations (lazy) → one terminal operation.
  • Streams do not change their source and can be used only once.
  • map: one-to-one; flatMap: one-to-many, flattened.
  • min, max, findFirst and reduce without identity return Optional.
  • Use IntStream and friends for numbers: sum, average, summaryStatistics.
  • groupingBy + downstream collectors build reports; partitioningBy splits into true/false.

Frequently asked questions

Are streams faster than loops?

Not necessarily – for simple work a loop can be slightly faster. Use streams for clarity; measure before optimising.

toList() vs collect(Collectors.toList())?

Stream.toList() (Java 16) returns an unmodifiable list; Collectors.toList() currently returns a modifiable ArrayList but makes no promise.

When should I use parallel streams?

For large, CPU-bound workloads with independent elements and no shared mutable state – and only after measuring.

Where can I learn more?

Read Java Streams and Java Collectors, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links