Professional Documents
Culture Documents
By
Shruti
Asst. Professor, LPU
Contents
Extracting data from an object using map
Describing the types of stream operations
Describing the Optional class
Describing lazy processing
Sorting a stream
Saving results to a collection using the collect method
Grouping and partition data using the Collectors class
Reduction Operations
min(), max() and count() represents the reduction operation in
Stream.
NOTE:
BinaryOperator is a functional interface that extends the
BiFunction functional interface. It defines the apply method.
T apply(T val, T val2)
Here, val stores the current result and val2 contains the next element.
import java.util.*; import java.util.stream.*;
class StreamDemo {
public static void main(String[] ar) {
ArrayList<Integer> myList = new ArrayList<>( );
myList.add(7); myList.add(18); myList.add(10);
myList.add(24); myList.add(17); myList.add(5);
One of the benefits that the stream library offers is the ability
to easily and reliably parallel process certain operations.
NOTE:
It returns a parallel stream based on the sequential stream that
invokes it.
If it is called on a stream that is already parallel, then the invoking
stream is returned.
Important
Stateless means that the operation does not rely on any state
information. Thus, each element is processed independently.
double result =
myList.parallelStream().reduce(1.0,
(a,b) -> a * Math.sqrt(b),
(a,b) -> a * b
);
NOTE:
We can switch a parallel stream to sequential by calling the
sequential( ) method, which is specified by BaseStream.
S sequential( )
Important
double productOfSqrRoots2 =
myList.parallelStream().reduce( 1.0,
(a,b) -> a * Math.sqrt(b));
//Collecting in a List
List<String> word = letters.stream().map(s ->
s.toUpperCase()).collect(Collectors.toList());
//Collecting in a Set
Set <String> word= letters.stream().map(s ->
s.toUpperCase()).collect(Collectors.toSet());
Grouping and Partitioning
Using Collectors
1. Display the names of all the Male employees having salary less
than 25000 in descending order of their id.
3. Spliterator<T> trySplit( )
tryAdvance()
It performs an action on the next element and then advances the
iterator.
Example:
Stream<String> myStream = myList.stream();
Spliterator<String> splitItr = myStream.spliterator();
while(splitItr.tryAdvance( s -> System.out.println(s) );
forEachRemaining()
Used to perform some action on each element collectively,
rather than one at a time.
Spliterator<T> trySplit( )