Java - Streams from generate() Function

Introduction

generate(Supplier<T> s) method uses the specified Supplier to generate an infinite sequential unordered stream.

The following code prints five random numbers greater than or equal to 0.0 and less than 1.0.

Stream.generate(Math::random)
      .limit(5)
      .forEach(System.out::println);

To use the generate() method to generate an infinite stream in which the next element is generated based on the value of the previous element, use a Supplier that stores the last generated element.

The following code prints five prime numbers after skipping the first 100:

Demo

import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    Stream.generate(new PrimeUtil()::next)
    .skip(100)/*from w  w w. j av  a 2s  .com*/
    .limit(5)
    .forEach(System.out::println);
  }
}

class PrimeUtil {
  private long lastPrime = 0L;

  // Computes the prime number after the last generated prime
  public long next() {
    lastPrime = next(lastPrime);
    return lastPrime;
  }

  // Computes the prime number after the specified number
  public static long next(long after) {
    long counter = after;

    // Keep looping until you find the next prime number
    while (!isPrime(++counter))
      ;

    return counter;
  }

  // Checks if the specified number is a prime number
  public static boolean isPrime(long number) {
    // <= 1 is not a prime number
    if (number <= 1) {
      return false;
    }

    // 2 is a prime number
    if (number == 2) {
      return true;
    }

    // Even numbers > 2 are not prime numbers
    if (number % 2 == 0) {
      return false;
    }

    long maxDivisor = (long) Math.sqrt(number);
    for (int counter = 3; counter <= maxDivisor; counter += 2) {
      if (number % counter == 0) {
        return false;
      }
    }

    return true;
  }
}

Result

Related Topics