In this tutorial, we will see how Java 8 Stream Generate Random String and Numbers.

Stream generate random String:

Stream provides generate method – It returns an infinite sequential unordered stream where each element is generated by the given supplier.

Syntax:

static <T> Stream<T>  generate(Supplier<T> s)

The random method takes Supplier as a parameter, generates random elements and returns the infinite sequential unordered stream.

How to Generate random String:

Creating a Supplier class which supplies the random string.

Generator.java
import java.util.Random;
import java.util.function.Supplier;

public class Generator implements Supplier<String> {
    Random random = new Random(50);
    char[] letters =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
    @Override
    public String get() {
        System.out.print(letters[random.nextInt(letters.length)]);
        return "" + letters[random.nextInt(letters.length)];
    }
}

Stream.random():

Generating random string length of 20

StreamGenerate.java
public class StreamGenerate {
    public static void main(String[] args) {
        String random_string = Stream.generate(new Generator())
                .limit(20)
                .collect(Collectors.joining());
        System.out.println(random_string);
    }
}

Output:

Terminal
NY3Q5NQSAQUUM9IA6LXQ

Stream generate random Numbers:

Generating random numbers (integers and doubles) using Stream.generate() method.

// Generating 10 random Integers
Stream.generate(new Random()::nextInt)
       .limit(10).forEach(System.out::println);
// Generating 10 random Doubles
Stream.generate(new Random()::nextDouble)
       .limit(10).forEach(System.out::println);

Output:

Terminal
-1196464118
-1593812527
-1724863181
259768096
-934357725
-192325390
-2083605141
865137992
760235079

0.4896064504440346
0.4426364500730168
0.9603767307360307
0.7014553531359498
0.7286628591385252
0.961113001747233
0.6084732423154003
0.5903369288532173
0.8575574428205311
0.6410731496668606

Done!

References:

Happy Learning 🙂

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment