Infinite sequential unordered stream

In order to create an infinite sequential unordered stream, we can rely on Stream.generate​(Supplier<? extends T> s). In this case, each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, and so on.

For example, let's assume that we have a simple helper that generates passwords of eight characters:

private static String randomPassword() {

String chars = "abcd0123!@#$";

return new SecureRandom().ints(8, 0, chars.length())
.mapToObj(i -> String.valueOf(chars.charAt(i)))
.collect(Collectors.joining());
}

Furthermore, we want to define an infinite sequential unordered stream that returns random passwords (Main is the class that contains the preceding helper):

Supplier<String> passwordSupplier = Main::randomPassword;
Stream<String> passwordStream = Stream.generate(passwordSupplier);

At this point, passwordStream can create passwords indefinitely. But let's create 10 such passwords:

List<String> result = passwordStream
.limit(10)
.collect(Collectors.toList());

One possible output is as follows:

213c1b1c, 2badc$21, d33321d$, @a0dc323, 3!1aa!dc, 0a3##@3!, $!b2#1d@, 0@0#dd$#, cb$12d2@, d2@@cc@d
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.39.144