Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

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


Published on

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.

Published in: Technology
  • Be the first to comment

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

  1. 1. Java 8 Streams & Common Operations By Harmeet Singh(Taara) (Java EE Developer) Email: Blog: Skype: harmeetsingh0013 Contact: Via Email or Skype
  2. 2. 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
  3. 3. Acknowledgment ➢ Special Thanks To My Parents. ➢ Thanks To All, Who Support Me or Not. ➢ Dedicated To My Teacher “Mr. Kapil Sakhuja” ➢ Thanks To Insonix.
  4. 4. 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 : Examples.git)
  5. 5. 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.
  6. 6. Higher-Order Functions ➢ Examples:
  7. 7. Effective Final Variable ➢ Effective final variables whose values is never changed after initialized. Imagine Adding a ‘final’ modifier to variable declaration. ➢ Example:-
  8. 8. 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.
  9. 9. 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:-
  10. 10. 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.
  11. 11. Method-References ➢ Example:- ➢ Method Reference Lambda Translation:-
  12. 12. 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:-
  13. 13. External-Iterators ➢ The iteration control by User manual.
  14. 14. 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
  15. 15. Stream’s Common Operations ➢ Stream is divided into 3 parts:- ○ Declaration ○ Intermediate ○ Termination ➢ Example:-
  16. 16. 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)
  17. 17. 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:
  18. 18. 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:
  19. 19. 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:
  20. 20. 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:
  21. 21. 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:
  22. 22. 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
  23. 23. Stream’s Common Operations ➢Now we solve the previous problem with the help of reduce Operation in Stream. This is Terminal Operation. Example:
  24. 24. 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);
  25. 25. 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();
  26. 26. 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.
  27. 27. 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.
  28. 28. 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.
  29. 29. 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.
  30. 30. 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.
  31. 31. 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.
  32. 32. 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.
  33. 33. Stream’s Collectors ➢ <T, K> Collector<CharSequence, ?, String> joining(CharSequence delimiter); ➢ This functions concat the input elements, separated by specify delimiter.
  34. 34. 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.
  35. 35. Optional Class
  36. 36. 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.
  37. 37. Leftover: The Important Topics We Didn’t Cover 1. Method Handlers 2. 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
  38. 38. 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” ( ava8-optional-2175753.html) Any Many More Like Dzone, StackOverflow etc.