**Stream API is used to process collections of objects. A stream in Java is a sequence of objects that supports various methods which can be pipelined to produce the desired result. **
There uses of Stream in Java are mentioned below:
Java Stream Features:
List<List<String>> listOfLists = Arrays.asList(
Arrays.asList("Reflection", "Collection", "Stream"),
Arrays.asList("Structure", "State", "Flow"),
Arrays.asList("Sorting", "Mapping", "Reduction", "Stream")
);
Stream<String> str= list.stream(); ->provides stream of values that can be used only once for operations related to stream like .map(), .filter(), .sorted() and then it is deleted from the memory.
List<String> result = list.stream()
.flatMap(List::stream) // Flatten the list of lists into a single stream
.filter(s -> s.startsWith("S")) // Filter elements starting with "S"
.map(String::toUpperCase) // Transform each element to uppercase
.distinct() // Remove duplicate elements
.sorted() // Sort elements
.peek(s -> intermediateResults.add(s)) // Perform an action (add to set) on each element
.collect(Collectors.toList());
// Print the final result
System.out.println("Final Result:");
result.forEach(System.out::println);
Output ==>
Final Result:
SORTING
STATE
STREAM
STRUCTURE
List<Integer> nums= Arrays.asList(2,3,4,5,6);
int result= nums.stream()
.map(n -> n*2)
.reduce(0, (a,b) -> a+b); //.reduce() method is used to calculate the sum of stream after processing
System.out.println(result);
Output
40