Java streams are a powerful and expressive feature introduced in Java 8 to facilitate functional-style programming and to enable efficient and parallel processing of collections.
Intermediate operations are operations that transform or manipulate the stream and return a new stream. They are often used in a chain to build a pipeline of operations.
Filter:
stream.filter(predicate)
Map:
stream.map(mapper)
FlatMap:
stream.flatMap(mapper)
Sorted:
stream.sorted(comparator)
Distinct:
stream.distinct()
Peek:
stream.peek(consumer)
Terminal operations are operations that produce a result or a side-effect. They trigger the execution of the stream pipeline.
forEach:
stream.forEach(consumer)
toArray:
stream.toArray()
reduce:
stream.reduce(identity, accumulator, combiner)
Optional
.collect:
stream.collect(collector)
count:
stream.count()
findFirst:
stream.findFirst()
Optional
.anyMatch, allMatch, noneMatch:
stream.anyMatch(predicate)
, stream.allMatch(predicate)
, stream.noneMatch(predicate)
min and max:
stream.min(comparator)
, stream.max(comparator)
findAny:
stream.findAny()
Optional
.toArray:
stream.toArray()
Example:
List<String> words = Arrays.asList("hello", "world", "java", "stream", "example");
// Example using stream operations
long count = words.stream()
.filter(word -> word.length() > 4)
.map(String::toUpperCase)
.sorted()
.count();
System.out.println("Count: " + count);