Stream API examples
A stream represents a sequence of elements and supports different kind of operations to perform computations upon those elements. There are two types of stream operations:
- Intermediate
- Terminal
We will see intermediate operations like filter, map, sorted where as forEach is a terminal operation.
List<String> list =
Arrays.asList("GAURAV", "ADITYA", "RISHAB", "MIHIKA", "RAJEEV");
list
.stream()
.filter(s -> s.startsWith("G"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
Such a chain of stream operations as seen in the above example is referred as operation pipeline.
A function is non-interfering when it does not modify the underlying data source of the stream.
We can see in the above example no lambda expression appears to modify list elements by adding or removing methods from the collection.
A function is stateless when the execution of the operation is deterministic, e.g. in the above example no lambda expression depends on any mutable variables which might change the execution state.
StreamAPIMethodUsesExample.java
package com.gaurav.stream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamAPIMethodUsesExample {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 100; i++) {
list.add(i);
}
/**
* Stream filter() example: We can use filter() method to check stream
* elements following a condition and generate a filtered list.
*
*/
Stream<Integer> sequentialStream = list.stream();
Stream<Integer> filteredNums = sequentialStream.filter(x -> x > 85);
System.out.println("Count of filtered Numbers greater then 85 is :");
filteredNums.forEach(x -> System.out.print(x + " "));
/**
* Stream sorted() example: We can use sorted() method to sort in
* natural as well as reverse order the stream elements by passing
* Comparator argument.
*/
Stream<String> namesStream1 = Stream.of("gaurav", "aditya", "rishab", "mihika", "987654");
List<String> reversedNames = namesStream1.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
System.out.println("\nStream sorting example in reverese order: " + reversedNames);
Stream<String> namesStream2 = Stream.of("GAURAV", "ADITYA", "RISHAB", "MIHIKA", "123456");
List<String> naturalSorting = namesStream2.sorted().collect(Collectors.toList());
System.out.println("Stream sorting example in natural order: " + naturalSorting);
/**
* Stream map() example: We can use map() to apply functions to an
* stream. I have used it to apply lower case function to a list of
* names.
*/
Stream<String> names = Stream.of("gauRAV", "Aditya", "riSHAB", "MIhika");
System.out.print("Map elements extracted in Lowercase by Stream is:" + names.map(s -> {
return s.toLowerCase();
}).collect(Collectors.toList()));
list = new ArrayList<Integer>();
for (int i = 100; i < 120; i++) {
list.add(i);
}
/**
* Stream count() example: We can use this to count
* the number of items available in the stream.
*/
Stream<Integer> numbersStream1 = list.stream();
System.out.println("\nTotal number of elements in the list stream is = " + numbersStream1.count());
/**
* Stream forEach() example: This can be used for iterating over the
* collections or stream. In place of iterator, We can use this.
*/
Stream<Integer> numbersStream2 = list.stream();
System.out.println("\nNumbers available in the list stream are = ");
numbersStream2.forEach(x -> System.out.print(x+","));
/** Stream match() examples: We can use anyMatch(), allMatch() and noneMatch() methods of stream */
Stream<Integer> numbersStream3 = list.stream();
System.out.println("\nIs the given stream contains 119 ? "+numbersStream3.anyMatch(i -> i==119));
//Output:Is the given stream contains 119 ? true
Stream<Integer> numbersStream4 = list.stream();
System.out.println("Is the given stream contains all elements less than 120 ? "+numbersStream4.allMatch(i -> i<120));
//Output:Is the given stream contains all elements less than 120 ? true
Stream<Integer> numbersStream5 = Stream.of(1,2,3,4,5);
System.out.println("Is the given stream doesn't contain 120? "+numbersStream5.noneMatch(i -> i == 120));
//Output:Is the given stream doesn't contain 120? true
/**
* Stream reduce() method: We can use reduce() to perform a reduction
* on the elements of the stream and return an Optional.
*/
Stream<Integer> numbersStream6 = Stream.of(1,2,3,4,5,6);
Optional<Integer> intOptional = numbersStream6.reduce((i,j) -> {return i*j;});
if(intOptional.isPresent()){
System.out.println("\nMultiplication of the all the available numbers in given stream are = "+intOptional.get());
}
/**
* Stream findFirst() example: we can use it to find the first character from
* a stream starting with G.
*/
Stream<String> numbersStream7 = Stream.of("ADITYA", "RISHAB", "MIHIKA","GAURAV", "TIA");
Optional<String> nameStartWithG = numbersStream7.filter(i -> i.startsWith("G")).findFirst();
if(nameStartWithG.isPresent()){
System.out.println("Name which is starting with G = "+nameStartWithG.get());
}
}
}
Output:
Count of filtered Numbers greater then 85 is :
86 87 88 89 90 91 92 93 94 95 96 97 98 99
Stream sorting example in reverese order: [rishab, mihika, gaurav, aditya, 987654]
Stream sorting example in natural order: [123456, ADITYA, GAURAV, MIHIKA, RISHAB]
Map elements extracted in Lowercase by Stream is:[gaurav, aditya, rishab, mihika]
Total number of elements in the list stream is = 20
Numbers available in the list stream are =
100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,
Is the given stream contains 119 ? true
Is the given stream contains all elements less than 120 ? true
Is the given stream doesn't contain 120? true
Multiplication of the all the available numbers in given stream are = 720
Name which is starting with G = GAURAV
No comments:
Post a Comment