Java - Stream Java Streams

Introduction

What Is a Stream?

A stream is a sequence of data elements supporting sequential and parallel aggregate operations.

Collections focus on storage of data elements whereas streams focus on aggregate computations.

The following code that uses a stream to compute the sum of all odd integers in the list:

Demo

import java.util.Arrays;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
    int sum = numbers.stream()
        .filter(n -> n % 2 == 1)/*from   w  w w .  ja  va2 s.  co  m*/
        .map(n -> n * n)
        .reduce(0, Integer::sum);
    System.out.println(sum);
  }
}

Result

You can compute the sum of squares of odd integers in the list in parallel.

Demo

import java.util.Arrays;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
    int sum = numbers.parallelStream()
        .filter(n -> n % 2 == 1)/*from   www  . ja  v a 2s  .co m*/
        .map(n -> n * n)
        .reduce(0, Integer::sum);
    System.out.println(sum);
  }
}

Result

Streams are designed to use internal iteration.

They provide an iterator() method that returns an Iterator to be used for external iteration of its elements.

If you ever need it, here is how to use it:

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
    // Get a list of integers from 1 to 5

    // Get an iterator from the stream
    Iterator<Integer> iterator = numbers.stream().iterator();
    while (iterator.hasNext()) {
      int n = iterator.next();
    }
  }
}