Java Tutorial

Java Streams

Streams let you filter, map, and reduce collections as a pipeline. Nothing runs until a terminal operation like collect or forEach.

filter and map

Call .stream() on a collection, then chain intermediate ops. filter keeps some elements; map transforms each one. The stream is not a new list until you collect or forEach.

Example

import java.util.List;

public class Main {
  public static void main(String[] args) {
    List.of(1, 2, 3, 4).stream()
        .filter(n -> n % 2 == 0)
        .map(n -> n * n)
        .forEach(n -> System.out.print(n + " "));
    System.out.println();   // 4 16
  }
}

collect into a List

Collectors.toList() (or .toList() on newer JDKs) materializes the pipeline into a real list you can keep.

Example

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

public class Main {
  public static void main(String[] args) {
    List names = List.of("Ada", "Lin", "Al");
    List longOnes = names.stream()
        .filter(s -> s.length() > 2)
        .map(String::toUpperCase)
        .collect(Collectors.toList());
    System.out.println(longOnes);   // [ADA, LIN]
  }
}

sum and match

mapToInt plus sum totals numbers. anyMatch /allMatch answer yes/no questions about the stream.

Example

import java.util.List;

public class Main {
  public static void main(String[] args) {
    List nums = List.of(8, 11, 5);
    int sum = nums.stream().mapToInt(n -> n).sum();
    boolean anyBig = nums.stream().anyMatch(n -> n > 10);
    System.out.println(sum);     // 24
    System.out.println(anyBig);  // true
  }
}

Intermediate ops are lazy. If you never call a terminal op, nothing in the pipeline runs — handy when you build a stream and pass it along.

sorted and distinct

sorted orders elements; distinct drops duplicates according toequals. Chain them when cleaning input.

Example

import java.util.List;

public class Main {
  public static void main(String[] args) {
    List.of(3, 1, 2, 1, 3).stream()
        .distinct()
        .sorted()
        .forEach(n -> System.out.print(n + " "));
    System.out.println();   // 1 2 3
  }
}

A stream can be consumed only once. After forEach or collect, create a new stream from the source if you need another pass.

Try It Yourself

Exercise: From List.of(2, 5, 8, 11), keep numbers greater than 5, double them, and print each with forEach.

Show solution
import java.util.List;

List.of(2, 5, 8, 11).stream()
    .filter(n -> n > 5)
    .map(n -> n * 2)
    .forEach(n -> System.out.print(n + " "));
System.out.println();

filter keeps 8 and 11; map turns them into 16 and 22.

Key Takeaways

  • Streams are pipelines: intermediate ops transform, terminal ops trigger execution.
  • filter, map, sorted, distinct are common steps.
  • collect, forEach, sum, and match methods finish the pipeline.
  • A stream is single-use — stream again from the collection for another pass.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.

Statistics

Mean via stream

A stream maps values to a double average without an explicit loop. mapToInt then average returns an OptionalDouble.

x̄ = (Σxᵢ) / n

Example

import java.util.List;

public class Main {
  public static void main(String[] args) {
    double mean = List.of(2, 4, 6, 8).stream()
        .mapToInt(n -> n)
        .average()
        .orElse(0);
    System.out.println(mean);
  }
}

Maths

Product with reduce

reduce folds a list into one value. Starting from 1, multiply each term to get a product.

Π xᵢ

Example

import java.util.List;

public class Main {
  public static void main(String[] args) {
    int product = List.of(2, 3, 4).stream().reduce(1, (a, b) -> a * b);
    System.out.println(product);
  }
}

FAQ: Java Streams

Common questions about this page.

What is the StudyGrid Java tutorial?

The StudyGrid Java tutorial is a full beginner-to-advanced track: syntax, types, input, loops, methods, classes, collections, generics, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run java streams examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn java streams in this Java Java lesson (Java Streams).

Is the Java editor the same as Try Python or Try C++?

No. Try Java compiles with javac at /java/try and shows stdout plus compiler messages. Try Python stays at /try. Try C++ stays at /cpp/try. Java lessons never open those editors.

Do I need to install a JDK to learn Java?

No. Open a chapter, click Try it in Java, and compile in the browser. You can also download a .java file and compile locally with javac.

Where should I start the Java tutorial?

Start at Java Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open Java Examples, then generics, map, and lambdas. Use Next at the bottom of each chapter.

Is the Java tutorial free?

Yes. The Java workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.