We usually use an iterator to process a collection.
List<String> words = ....;
long count = 0;
for(String w : words){
if(w.length() > 10){
count++;
}
}
An iterator generates all elements from a collection as a sequence.
Alternative Approach
long count = words.stream().filter(w -> w.length() >10).count();
Stream processing is declarative.
Processing can be parallelized.
long count = words.paralleStream().filter(w->w.length()>10).count();
Lazy Evaluation is possible.
A stream does not actually stores its elements.
- Elements are stores in the underlying collection.
- Or is generated by a function, on demand.
Stream operations are non-destructive
- Input stream is untouched.
Apply stream()
to a collection.
Collections
interface.List<String> wordlist = .... ;
Stream<String> wordstream = wordlist.stream();
Use static method Stream.of()
for arrays.
String[] wordarr = .... ;
Stream<String> wordstream = Stream.of(wordarr);
Static method: Stream.generate()
generates a stream from a function.
Stream<String> echos = Stream.generate( () -> "Echo" ) ;
Stream<Double> randomds = Stream.generate(Math::random)