Java Concurrency and Multithreading Java 8 Features

What is Stream.generate() in Java 8?

The Stream.generate() method in Java is a powerful feature introduced in the java.util.stream.Stream class. It allows you to create an infinite sequential unordered stream where each element is generated by a provided Supplier. Let’s break it down:

  • Purpose:
    • The Stream.generate(Supplier<T> s) method creates an infinite stream of elements based on the provided Supplier.
    • This is suitable for generating constant streams, streams of random elements, or any other custom sequence.
  • Method Signature: static <T> Stream<T> generate(Supplier<T> s)
    • Here:
      • Supplier<T> is a functional interface representing a supplier of values.
      • T is the type of stream element.
  • Example 1: Generating a Stream of Random Integers:
Java
import java.util.*;
import java.util.stream.Stream;
public class RandomIntegerStream {
    public static void main(String[] args) {
        Stream.generate(new Random()::nextInt).limit(5).forEach(System.out::println);
    }
}
  • Example 2: Generating a Stream of Random Doubles:

Java
import java.util.*;
import java.util.stream.Stream; 
public class RandomDoubleStream { 
    public static void main(String[] args) { 
        // Generate 8 random Double values 
        Stream.generate(new Random()::nextDouble) .limit(8) .forEach(System.out::println); 
    } 
} 
//Output: 0.5390254520295368 0.8477297185718798 0.23703352435894398 0.09156832989674057 0.9671295321757734 0.9989670394813547 0.8909416330715489 0.08177639888829968

In summary, Stream.generate() provides a convenient way to create custom streams with dynamically generated elements. Whether you’re dealing with random data or other sequences, this method empowers you to work with infinite streams efficiently! 🚀

Avatar

Neelabh

About Author

As Neelabh Singh, I am a Senior Software Engineer with 6.6 years of experience, specializing in Java technologies, Microservices, AWS, Algorithms, and Data Structures. I am also a technology blogger and an active participant in several online coding communities.

You may also like

Blog Java Java 8 Features

Avoid NullPointerException in Java with Optional: A Comprehensive Guide

Are you tired of dealing with avoid NullPointerExceptions(NPEs) in your Java code? Look no further than the Optional class introduced
Blog Java Java 8 Features

Unlocking the Power of Java 8 Streams: A Guide to Efficient Data Processing

What are Java 8 Streams? At its core, a stream in Java 8 is a sequence of elements that facilitates