Inheritance
Getting started with Java
Streams
Streams
Using Streams
Consuming Streams
Creating a Frequency Map
Infinite Streams
Collect Elements of a Stream into a Collection
Using Streams to Implement Mathematical Functions
Parallel Stream
Flatten Streams with flatMap
Creating a Stream
Finding Statistics about Numerical Streams
Using IntStream to iterate over indexes
Converting an iterator to a stream
Concatenate Streams
Using Streams of Map.Entry to Preserve Initial Values after Mapping
Using Streams and Method References to Write Self-Documenting Processes
Finding the First Element that Matches a Predicate
Reduction with Streams
IntStream to String
Get a Slice of a Stream
Converting a Stream of Optional to a Stream of Values
Create a Map based on a Stream
Joining a stream to a single String
Streams of Primitives
Sort Using Stream
Stream operations categories
Generating random Strings using Streams
Collect Results of a Stream into an Array
Closing Streams
Exceptions
Collections
Lambda Expressions
Generics
File I/O
Arrays
Interfaces
Maps
Strings
InputStreams and OutputStreams
Default Methods
Classes and Objects
Basic Control structures
Concurrent Programming Threads
Console I/O
Singletons
Visibility controlling access to members of a class
Regular Expressions
Autoboxing
Documenting Java Code
Executor, ExecutorService and Thread pools
Object Class Methods and Constructor
JAXB
Primitive Data Types
Networking
Optional
Enums
HttpURLConnection
Annotations
Audio
Data Class
Calendar and its Subclasses
Nashorn JavaScript engine
Java Native Interface (JNI)
Remote Method Invocation (RMI)
Iterator and Iterable
Operators
Asserting
Scanner
Properties Class
Preferences
Reflection API
Constructors
ByteBuffer
Serialization
JSON in Java
Random Number Generation
Recursion
Polymorphism
StringBuilder
Refernce Data Types
Bit Manipulation
Java Agents
Encapsulation
Type Conversion
BigInteger
BigDecimal
RSA Encryption
Varargs Variable Arguments
ThreadLocal
Logging
static keyword
Disassembling and Decompling
Resources on classpath
log4j, log4j2
JVM Flags
Oracle Official Code Standard
Character encoding
Java Memory Management
Immutable Objects
Object Cloning
Alternative Collections
Lists
BufferedWriter
LocalTime
Sets
Comparable and Comparator
JVM Tool Interface
Nested and Inner Classes
Apache Commons Lang
Getters and Setter
The Classpath
Bytecode Modification
XML Parsing using JAXP
Reference Types
Localization and Internationalization
JAX-WS
XML XPath Evaluation
Performance Tuning
Parallel programming with ForkJoin framework
Common Pitfalls
Non-Access Modifiers
Java Compiler
XJC
Installing Java Standard Edition
Process
Command line argument processing
Dates and Time using java.time
Fluent Interface
XOM - XML Object Model
Just in Time JIT compiler
FTP File Transfer Protocol
Java Native Access JNI
Modules
Pitfalls - exceptions
Pitfalls - language syntax
ServiceLoader
ClasssLoader
Object References
Pitfalss - performance
Creating Images Programmatically
Applets
NIO Networking
New File I/O
Secure objects
Pitfalls - threads and concurrency
Splitting a string into fixed length parts
Pitfalls - nulls and NullPointerException
SecurityManager
JNDI
super keyword
java.util.Objects class
Java command: java and javaw
Atomic types
Floating Point Operations
Converting to and from strings
sun.misc.Unsafe
Java Memory Model
Java deployment
Java plugin system implementations
Queues and deques
Runtime commands
NumberFormat
Security and Cryptograhy
Java Virtual Machine JVM
Unit Testing
JavaBean
Expressions
Literals
Java SE 8 Features
Java SE 7 Features
Packages
Concurrency and Money
Concurrent Collections
Using ThreadPoolExecutor in multi-threaded applications
Java Editions, versions, releases and distributions
Dynamic method dispatch
JMX
Security and cryptography
Generating Java Code
JShell
Benchmarks
Collection Factory Methods
Multi-release JAR files
Stack-Walking API
TreeMap and TreeSet
Sockets
Java Sockets
Using other scripting languages in Java
Functional interfaces
List vs. set
2D graphics
Reflection
Deque interface
Enum Map
EnumSet class
Local Inner class
Java Print Service
Immutable class
String Tokenizer
File upload to S3 / AWS
Readers and writers
Hashtable
Enum starting with a number
SortedMap
WeakHashMap
LinkedHashMap
StringBuffer
Choosing Collections
C++ Comparison
CompletableFuture
Contributors

Generating random Strings using Streams

suggest change

It is sometimes useful to create random Strings, maybe as Session-ID for a web-service or an initial password after registration for an application. This can be easily achieved using Streams.

First we need to initialize a random number generator. To enhance security for the generated Strings, it is a good idea to use SecureRandom.

Note: Creating a SecureRandom is quite expensive, so it is best practice to only do this once and call one of its setSeed() methods from time to time to reseed it.

private static final SecureRandom rng = new SecureRandom(SecureRandom.generateSeed(20)); 
//20 Bytes as a seed is rather arbitrary, it is the number used in the JavaDoc example

When creating random Strings, we usually want them to use only certain characters (e.g. only letters and digits). Therefore we can create a method returning a boolean which can later be used to filter the Stream.

//returns true for all chars in 0-9, a-z and A-Z
boolean useThisCharacter(char c){
    //check for range to avoid using all unicode Letter (e.g. some chinese symbols)
    return c >= '0' && c <= 'z' && Character.isLetterOrDigit(c);
}

Next we can utilize the RNG to generate a random String of specific length containing the charset which pass our useThisCharacter check.

public String generateRandomString(long length){
    //Since there is no native CharStream, we use an IntStream instead
    //and convert it to a Stream<Character> using mapToObj.
    //We need to specify the boundaries for the int values to ensure they can safely be cast to char
    Stream<Character> randomCharStream = rng.ints(Character.MIN_CODE_POINT, Character.MAX_CODE_POINT).mapToObj(i -> (char)i).filter(c -> this::useThisCharacter).limit(length);

    //now we can use this Stream to build a String utilizing the collect method.
    String randomString = randomCharStream.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();
    return randomString;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents
11 Maps
26 JAXB
30 Enums
33 Audio
76 Lists
79 Sets
90 JAX-WS
97 XJC
107 Modules
115 Applets
123 JNDI
151 JMX
154 JShell
160 Sockets