[go: up one dir, main page]

0% found this document useful (0 votes)
246 views25 pages

Streams Api

The document discusses the key features and methods of Java Streams API. Some main points: - Streams allow processing of collections through intermediate and terminal operations like filter, map, reduce etc in a declarative way and avoid iterating manually. - Streams operations are lazy and pipelined - intermediate operations return streams and are evaluated late during terminal operation. - Common stream methods include filter, map, reduce, collect, match, find, sorted, limit for selecting, transforming and aggregating stream elements. - Optional class represents optional values and has methods like of, empty, ifPresent to work with values that may be absent.

Uploaded by

Sravani Prasad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
246 views25 pages

Streams Api

The document discusses the key features and methods of Java Streams API. Some main points: - Streams allow processing of collections through intermediate and terminal operations like filter, map, reduce etc in a declarative way and avoid iterating manually. - Streams operations are lazy and pipelined - intermediate operations return streams and are evaluated late during terminal operation. - Common stream methods include filter, map, reduce, collect, match, find, sorted, limit for selecting, transforming and aggregating stream elements. - Optional class represents optional values and has methods like of, empty, ifPresent to work with values that may be absent.

Uploaded by

Sravani Prasad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

STREAMS API

Streams: Collection of framework/Group of objects that supports various methods


Introduced in java8
Performs Bulk operations
Reduces code length

Colletion vs Stream:
If we want to represent a group of objects as a single entity then it is represented as
collections

But if we want to process objects from the collection then we should go for streams.

……..where concepts of collections is applicable,stream concepts can be applied there………..


Features of Java stream?

• A stream is not a data structure instead it takes input from the


Collections, Arrays, or I/O channels.
• Streams don’t change the original data structure, they only provide the
result as per the pipelined methods.
• 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.
CHARACTERSTICS OF STREAM
1.Sequence of characters--------- sequence of elements.
2.Source -------- takes collection,arrays,i/o devices as input
3.Aggregate operations -----supports filter,map,reduce,limit,find,match
4.Automatic iterations
5.Pipelining--------most of the stream operations return stream itself
HOW THE STREAM IS CREATED
stream() [method]is an interface
It was defined in java.util.stream package

Syntax:
Stream s=collection.Stream();
On the collection we are calling a stream method at the same time we
are storing it as stream method
EXAMPLE:
public class OwnDemo {
public static void main(String[] args) {
//create a stream from sources
Collection<String>collection=Arrays.asList("java","programming");
Stream<String> stream1=collection.stream(); //syntax of stream
stream1.forEach(System.out::println);
}
}
Here we used (System.out::println); and forEach in streams
Creating a stream of an array
public class OwnDemo {
public static void main(String[] args) {
Stream<String>stream=Stream.of("a","b","c");
stream.forEach(System.out::println);
}
}
Output:
a
b By using list and set , you can create streams
it will save the memory a,d reduce the size of the code
c
WITHOUT STREAM
public static void main(String[] args)
{
Set hashset= new HashSet();
hashset.add("aman");
hashset.add("akshatha");
hashset.add("arman");
hashset.add("arman");
hashset.add("aayush");
System.out.println(hashset);
Iterator i=hashset.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
WITH STREAM
• List<String>list=Arrays.asList("welcome","to","my","organization");
• Stream<String> stream2=list.stream(); // prints like a list
• stream2.forEach(System.out::println); //in sequential order

• List<String>list=Arrays.asList("welcome","to","my","organization");
• Set<String>set=new HashSet<>(list); //prints like a hashset
• Stream<String> stream3=set.stream(); elements are in random order
• stream3.forEach(System.out::println);
ForEach()
Method iterates through every element in the stream
Without stream:
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
for (Integer element : list) {
System.out.print(element + " ");}

With stream:
List list1 = Arrays.asList(1,3,5,7);
//list1.stream().forEach((k) -> {System.out.print(k + " ");});
list1.stream().forEach(System.out::println);
AGGREGATE OPERATIONS
It is a higher order function that applies a behaviour on elements in
stream
------filter(),map(),reduce(),limit(),find(),match() e.t.c
There are two types in aggregate operations
1.Intermediate operations
a.stateful-store information from prior invocation
distinct(),skip(),sorted()
b.stateless-do not store information from any prior invocation stack
filter(),map(),flatMap(),limit(),takeWhile(),dropWhile()
FILTER()
Used to select elements according to the predicate parameter passed
Syntax:Stream<T> filter(Predicate<? super T> predicate)
Map()
Map method maps the elements in the collection to other objects
according to the predicate based as parameter
Example:
List<Integer> list1 = Arrays.asList(11,22,44,21);
List<Integer> answer = list1.stream().map(x x*x).collect (Collectors.toList());
System.out.println(answer);

It maps list as squares output:


[121, 484, 1936, 441]
Collect()
Returns the outcome of intermediate operations
Example:
List<Integer> list = Arrays.asList(23, 43, 12, 25);
IntSummaryStatistics stats = list.stream().collect(Collectors.summarizingInt(i ->
i + i));
System.out.println("Sum:"+stats.getSum());

Gives us output as sum

output:
sum:206
Min(),Max(),Sum(),Count()
MIN()--------gives minimum data in the list as result
MAX()--------gives maximum data in the list as result
SUM()--------gives sum of the data in the list as output
COUNT()------- gives number of data in the list as output
• //calculate total amount of food
double SumOfPrice=foodlist.stream().collect(Collectors.summingDouble(id-
>id.price));
System.out.println( SumOfPrice);

• //calculating max food


Food min= foodlist.stream().min((a,b)->a.price>b.price?1:-1).get();
System.out.println(min.price);

• //calculating max food


Food max= foodlist.stream().max((a,b)->a.price>b.price?1:-1).get();
System.out.println(max.price);

//calculating count
double countPrice=foodlist.stream().filter(a->a.price>120).count();
System.out.println(countPrice);
LIMIT()
Stream<T> limit(long N) //syntax

Where N is the number of elements the stream should be limited to and this function returns new stream as output

The limit(long N) is a method of java.util.stream.Stream object.


This method takes one (long N) as an argument and returns a stream of size no more than N.
MATCH()
Match returns true if any element of the stream matches the
provided predicate, otherwise false. If Stream is empty then
false is returned and the predicate is not evaluated.
Two types: 1.MatchAll 2.MatchAny
1.The type matchall means the all elements should be match
with given input. If match it returns true,otherwise false
2.The type matchany means any one of the element should
be match with given input. If match it returns true,otherwise
false
boolean anyMatch(Predicate<? super T> predicate) //syntax
REDUCE()
we need to perform operations where a stream reduces to single resultant value,
for example, maximum, minimum, sum, product, etc.
Reducing is the repeated process of combining all elements. reduce operation
applies a binary operator to each element in the stream where the first argument
to the operator is the return value of the previous application and second
argument is the current stream element.

T reduce(T identity, BinaryOperator<T> accumulator); // syntax


Where, identity is initial value of type T and accumulator is a
function for combining two values.
Find()
The Java 8 Stream API introduced two methods that are often
misunderstood: findAny() and findFirst().
Syntax:
Optional<String> result=list.stream().findAny();
Optional<String> result =list.stream().findFirst();
Sorted()
The method sorted() will sort the elements (Strings,integers) in
ascending or decending order

We can sort the elements by using streams,comparable and


comparator methods
Stream<T> sorted(Comparator<? super T> comparator)
Optional()
The stream() method of java.util.Optional class in Java is used to get the
sequential stream of the only value present in this Optional instance. If there
is no value present in this Optional instance, then this method returns returns
an empty Stream.
// creating an Optional method
        Optional<Integer> op = Optional.of(9455);
  
        // printing value
        System.out.println("Optional: "+ op);
  
        // Stream
        System.out.println("Getting the Stream:");
        op.stream().forEach(a->System.out.println(a);
Methods in optional():
Optional.empty()
Optional.of()
Optional.ofNullable()
ifPresentOrElse()
Optional.of()
The of() method of java.util.Optional class in Java is used to get an
instance of this Optional class with the specified value of the specified
type.
Syntax: public static <T> Optional<T> of(T value)
EXAMPLE:
// create a Optional
        Optional<Integer> op= Optional.of(9455);
  
        // print value
        System.out.println("Optional: "+ op);
Optional.ofNullable()
The ofNullable() method of java.util.Optional class in Java is used to get an instance
of this Optional class with the specified value of the specified type. If the specified
value is null, then this method returns an empty instance of the Optional class.
//syntax: public static <T> Optional<T> ofNullable(T value)

EXAMPLE:
Optional<String> op2
            = Optional.ofNullable(null);
  
        // print value
        System.out.println("Optional 2: "+ op2);because we given null

Returns output as Optional 2:empty because we given null

You might also like