codegurukool.com · Free coding tutorials & online compiler

Home › Java Tutorial › Java lambdas and streams

Java lambdas and streams

Process collections in a pipeline.

A lambda is a short anonymous method: n -> n * n. A stream chains steps such as filter, map and sum over a collection. System.out::println is a method reference.

Commands in this lesson

filter

Definition: Builds a new array with only the items that pass a test.

Syntax:

array.filter(function);

Example:

console.log([1, 2, 3, 4].filter(function(x){ return x % 2 === 0; }));

map

Definition: Builds a new array by transforming each item.

Syntax:

array.map(function);

Example:

console.log([1, 2, 3].map(function(x){ return x * 2; }));

Example code

import java.util.*;

public class Main {
  public static void main(String[] args) {
    List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);
    nums.stream()
        .filter(n -> n % 2 == 0)
        .map(n -> n * n)
        .forEach(System.out::println);
    int total = nums.stream().mapToInt(Integer::intValue).sum();
    System.out.println("Total " + total);
  }
}

Run this code in the online editor

← Java exceptionsJava user input →