38
Java 8 Streams & Common Operations By Harmeet Singh(Taara) (Java EE Developer) Email: [email protected] Blog: http://harmeetsingh13.blogspot.in Skype: harmeetsingh0013 Contact: Via Email or Skype

Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Embed Size (px)

DESCRIPTION

In this, we are discuss about Java 8 Streams. Common Operations . Java 8 Streams are huge topic, so i am not cover all the things, but try to cover the basics operations of Streams. Before this, please refer my previous presentation "Functional programming in java 8", because of clear some basic concept for functional programming. For the reference use Java 8 API docs.

Citation preview

Page 1: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Java 8 Streams&

Common Operations

By Harmeet Singh(Taara)(Java EE Developer)

Email: [email protected]: http://harmeetsingh13.blogspot.in

Skype: harmeetsingh0013Contact: Via Email or Skype

Page 2: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Contents

➢ Introduction➢ High-Order Functions➢ Effective Final Variables➢ Lexical-Scoping➢ Method References ➢ Internal-Iterators➢ External-Iterators➢ Stream’s Common’s Operation➢ Stream’s Collectors➢ Optional Class ➢ Leftover: The Things We Didn’t Cover

Page 3: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Acknowledgment

➢ Special Thanks To My Parents.

➢ Thanks To All, Who Support Me or Not.

➢ Dedicated To My Teacher “Mr. Kapil Sakhuja”

➢ Thanks To Insonix.

Page 4: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Introduction

Today, We cover Java 8 Stream API’s for remove some ‘Boilerplate Code’ from our daily programming. In Java, Some time we need to write some common practices with our collections for fetching the elements and do some operations.

This make’s our code dirty. Java 8 Streams provide some powerful operations for our collections libraries. It is basically perform operation like SQL queries on java collections.

(Download Examples : https://github.com/harmeetsingh0013/Java8-Streams-Examples.git)

Page 5: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Higher-Order Functions

➢ In OO-Programming we’re using passing objects to methods, creating Objects with in method and returning objects from within method.

➢ Higher-Order Functions do to functions what methods did to objects.

➢ With Higher-Order Functions we can:-○ Pass Functions-to-Functions.○ Create Functions-within-Functions.○ Return Functions-from-Functions.

Page 6: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Higher-Order Functions

➢ Examples:

Page 7: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Effective Final Variable

➢ Effective final variables whose values is never changed after initialized. Imagine Adding a ‘final’ modifier to variable declaration.

➢ Example:-

Page 8: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Lexical-Scoping

➢ Lexical-Scoping is the way to declare, specific-scope of variables and it is only accessible with in that region.

➢ Two Types Of Lexical Scope.○ Static Lexical-Scope.○ Dynamic Lexical-Scope.

➢ Static Lexical-Scope:- The Scope of variable is declare at compile phase.

Page 9: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Lexical-Scoping

➢ Dynamic Lexical-Scope:- In this, First look for a local definition of a variable. If isn’t find, we look up the calling stack for a definition.

➢ Example:-

Page 10: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Method-References

➢ Method References gives you compact, easy-to-read lambda expressions for method that already have a name.

➢ Example:

() -> “string”.length();

TO

String::length;

➢ There are FOUR types of method reference:-○ Reference to a static method.○ Reference to an instance method of a particular

object.○ Reference to an instance method of an arbitrary

object of a particular type.○ Reference to a constructor.

Page 11: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Method-References

➢ Example:-

➢ Method Reference Lambda Translation:-

Page 12: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Internal-Iterators

➢ The iteration control by iterator not by user.➢ In this, user pass only the expression, that apply

on our Collection or Data-Structures. ➢ User only need to concentrate on Business logic. ➢ Example:-

Page 13: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

External-Iterators

➢ The iteration control by User manual.

Page 14: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Common Operations

➢ A Stream is a tool for building up complex operations on collections using functional approach.

➢ The streams are act as a commands in unix operating system, in which one command output is input of another command.

➢ Stream create pipeline for performing operations. These pipeline is also perform as parallel.

➢ Streams are also deal which Primitives type. But only with ‘int’, ‘long’ and ‘double’.

➢ Java 8 Steam provide ome special interfaces for primitive types as follow○ LongStream○ IntStream○ DoubleStream

Page 15: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Common Operations

➢ Stream is divided into 3 parts:-○ Declaration○ Intermediate○ Termination

➢ Example:-

Page 16: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Common Operations

➢ Stream Intermediate Operations are lazily loading. Without Termination Operation, the Intermediate operation not perform any action. When termination operation found the intermediate operation perform task.

➢ There are lots of Intermediate and Termination operations, but some important we discuss as follow:-○ filter(Predicated<? super T> predicate)○ map(Function<? super T, ? extends R> mapper)○ flatMap(Function<? super T, ? extends Stream<?

super R>> mapper)○ forEach(Consumer<? super T> action)○ peek(Consumer<? super T> action)○ reduce(BinaryOperator<T> accumulator)

Page 17: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Common Operations

➢ Stream<T> filter(Predicated<? super T> predicate);

filter build up the Stream recipe, but don’t force this recipe to be used. They provide lazy behaviour.

Example:

Page 18: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Common Operations

➢ <R> Stream<R> map(Function<? super T, ? extends R> mapper);

map If we want to convert one type of value to another type, map gives you the way “Apply Function to a Stream of values, producing another stream of the new values”.

Example:

Page 19: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Common Operations

➢ <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? super R>> mapper);

flatMap If we have multiple Streams of same type, and we need to concat all the streams together and return one common Stream, Then flatmap provide the way concatenates all the stream together

Example:

Page 20: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Common Operations

➢ void forEach(Consumer<? super T> action);

forEach It is a Terminal Operation, perform an action for each element of the stream. The behaviour of this operation is explicitly nondeterministic.

Example:

Page 21: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Common Operations

➢ Stream<T> peek(Consumer<? super T> action);

peek, It is an Intermediate Operation, performing an provided action on each element as elements are consumed from the resulting stream.

Example:

Page 22: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Common Operations

➢ Stream<T> reduce(BinaryOperator<T> accumulator);

➢ reduce It is based on reduction operation, take a sequence of input elements and combine them into single summary result by repeated application of a combining operation such as :-○ Finding the sum.○ Maximum of set of numbers. ○ Accumulating elements into a list.

➢ reduce, Operation Follows reduce pattern

Page 23: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Common Operations

➢ Now we solve the previous problem with the help of reduce Operation in Stream. This is Terminal Operation.

Example:

Page 24: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Collectors

➢ Java 8 Streams have rich of collectors, which provide some interesting operations perform on collections, like in sql queries group by, order by etc.

➢ Today we discuss some important collectors :- ○ collect(Collector<? super T, A, R> collector);○ toList(), toSet() and toMap();○ toCollection(Supplier<C> collectionFactory);○ maxBy, minBy and averagingInt(ToIntFunction<? super

T> mapper);○ partitioningBy(Predicate<? super T> preidicate);○ groupingBy(Function<? super T, ? extends K>

classifier);○ joining(CharSequence delimiter, CharSequence

prefix, CharSequence suffix);

Page 25: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Collectors➢ <R, A> R collect(Collector<? super T, A, R> collector);➢ The Method is a reduce operation that’s useful for

transforming the collection into another form, often a mutable collection.

➢ This method can perform parallel additions, as appropriate, into different sublists, and then merge them in a thread-safe manner into a large list.

➢ This is a Terminal Operation. ➢ The version of collect method accept Collector

object and Java provide us Collectors Utility class, which have several utility methods, used for generate lists, set and map. Methods as follow:-○ toList();○ toSet();○ toMap();

Page 26: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Collectors➢ <T> Collector<T, ?, List<T>> toList();➢ The Method return the List that accumulates the

input element into a new List. There is no guarantees on the type, mutability, serializability or thread-safety of the List return.

➢ There is no-guarantee it produce the implementation of ArrayList or other. If we need Basic Collections implementation use toCollection() method.

Page 27: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Collectors➢ <T> Collector<T, ?, Set<T>> toSet();➢ The Method return the Set that accumulates the input

element into a new Set. There is no guarantees on the type, mutability, serializability or thread-safety of the List return.

➢ There is no-guarantee it produce the implementation of HashSet or other. If we need Basic Collections implementation use toCollection() method.

Page 28: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Collectors➢ <T, K, U> Collector<T, ?, Map<K,U>> toMap(Function<?

super T, ? extends K> keyMapper, Function<? super T, ? extends K> valueMapper);

➢ The Method return the Map whose keys and values are the result of applying the provided mapping functions to the input element.

➢ If the mapped keys contain duplicates an IllegalStateException is thrown when the collection operation is performed.

Page 29: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Collectors➢ <T> Collector<T, ?, Optional<T>> maxBy(Comparator<?

super T> comparator);➢ Produces the maximal element from given stream,

according to given Comparator and return Optional Object.

Page 30: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Collectors➢ <T> Collector<T, ?, Double> minBy(ToIntFunction<? super

T> mapper);➢ Produces the arithmetic-mean of an integer-valued

function applied to the input elements. If no element are present, result is 0.

Page 31: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Collectors➢ <T> Collector<T, ?, Map<Boolean, List<T>>>

partitioningBy(Predicated<? super T> predicate);➢ This is a collector that takes a stream and partitions

its content into two groups.➢ It uses a predicate to determine whether an element

should be a part of true group or the false group and returns a Map from Boolean to a List of values.

Page 32: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Collectors➢ <T, K> Collector<T, ?, Map<K, List<T>>>

groupingBy(Function<? super T, ? extends K> classifier);

➢ This functions map element to some Key type K.

Page 33: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Stream’s Collectors➢ <T, K> Collector<CharSequence, ?, String>

joining(CharSequence delimiter);➢ This functions concat the input elements, separated

by specify delimiter.

Page 34: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Optional Class

➢ Null is a EVIL➢ Tony Hoare wrote about null “I call it my billion-dollar

mistake. It was the invention of the null reference in 1965. I couldn’t resist the temptation to put in a null reference, simply because it was easy to implement. “

➢ The alternative from functional programming is using a Option Type, That can contain some value or not.

➢ The Optional Class includes methods to explicitly deal with cases where a value is present or absent.

➢ Advantage of Optional Class forces to think about the case when value is not present.

Page 35: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Optional Class

Page 36: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Optional Class

➢ Following are the operations we perform with Optional:- ○ Creating Optional Object○ Do Something if value is present. ○ Default values and actions.○ Rejecting Certain values using the filter

method.○ Extracting the transform values using the map

method. ○ Cascading the Optional object using the flatMap

method.

➢ The above method we discuss filter, map and flatMap are not stream methods, they are itself optional class methods. For further methods refer Java 8 API docs.

Page 37: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Leftover: The Important Topics We Didn’t Cover

1. Method Handlers2. Default Methods And Static Methods In

Interface.3. Java 8 Date API.4. InvokeDynamic.5. Concurrency In Lambda’s.6. Parallel Streams.7. Design And Architect Principals. 8. Code Refactoring. 9. Custom Collectors. 10.Deep Dive in Optional Class

Page 38: Java 8 Streams And Common Operations By Harmeet Singh(Taara)

References

➢ Special Thanks to Richard Warburton for “Java 8 lambdas”.

➢ Venkat Subramaniam “Functional Programming In Java”

➢ Oracle Java API Docs➢ Raoul-Gabriel Urma “Tierd Of null Pinter

Exception” (http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html)

Any Many More Like Dzone, StackOverflow etc.