Stream: - It is an API introduced in Java 8 used to process a collection of objects. It primarily has two types of operations: -
It is a combination of one or more intermediate operations followed by a terminal operation. Each intermediate operation is lazily executed and returns a stream as a result, hence, various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.
Some common intermediate and terminal operations are as follows: -
JAVA1<R> Stream<R> map(Function<? super T, ? extends R> mapper)
JAVA1Stream<T> filter(Predicate<? super T> predicate)
JAVA1Stream<T> sorted() 2Stream<T> sorted(Comparator<? super T> comparator)
JAVA1<R, A> R collect(Collector<? super T, A, R> collector)
Sample code depicting the usage of above operations: -
JAVA1import java.util.*; 2import java.util.stream.Collectors; 3 4public class SampleStreamOperations{ 5 public static void main(String[] args) { 6 // Sample data 7 List<String> names = Arrays.asList( 8 "Reflection", "Collection", "Stream", 9 "Structure", "Sorting", "State" 10 ); 11 12 // forEach: Print each name 13 System.out.println("forEach:"); 14 names.stream().forEach(System.out::println); 15 16 // collect: Collect names starting with 'S' into a list 17 List<String> sNames = names.stream().filter(name -> name.startsWith("S")).collect(Collectors.toList()); 18 System.out.println("\ncollect (names starting with 'S'):"); 19 sNames.forEach(System.out::println); 20 21 // reduce: Concatenate all names into a single string 22 String concatenatedNames = names.stream().reduce( 23 "", 24 (partialString, element) -> partialString + " " + element 25 ); 26 System.out.println("\nreduce (concatenated names):"); 27 System.out.println(concatenatedNames.trim()); 28 29 // count: Count the number of names 30 long count = names.stream().count(); 31 System.out.println("\ncount:"); 32 System.out.println(count); 33 34 // findFirst: Find the first name 35 Optional<String> firstName = names.stream().findFirst(); 36 System.out.println("\nfindFirst:"); 37 firstName.ifPresent(System.out::println); 38 39 // allMatch: Check if all names start with 'S' 40 boolean allStartWithS = names.stream().allMatch(name-> name.startsWith("s")); 41 System.out.println("\nallMatch (all start with 'S'):"); 42 System.out.println(allStartWithS); 43 44 // anyMatch: Check if any name starts with 'S' 45 boolean anyStartWithS = names.stream().anyMatch( 46 name -> name.startsWith("S") 47 ); 48 System.out.println("\nanyMatch (any start with 'S'):"); 49 System.out.println(anyStartWithS); 50 } 51}