Java8 training - Class 1

22
Java 8 Training -Marut Singh Email: [email protected] http:// www.marutsingh.com/ https://github.com/singhmarut/java8training http://marutsingh.com/

Transcript of Java8 training - Class 1

Page 1: Java8 training  - Class 1

http://marutsingh.com/

Java 8 Training-Marut Singh

Email: [email protected]://www.marutsingh.com/

https://github.com/singhmarut/java8training

Page 2: Java8 training  - Class 1

About Me

12 years in Software Industry Build software in Project Management, Banking, Education,

Ecommerce C++,C #.Net, Java, Scala, Akka, Spring, Node.JS, Vert.x, RDBMS,

MongoDB [email protected]

http://marutsingh.com/

Page 3: Java8 training  - Class 1

http://marutsingh.com/

1. Collections Streams, and Filters

Iterating through a collection using lambda syntax Describing the Stream interface Filtering a collection using lambda expressions Calling an existing method using a method reference Chaining multiple methods together Defining pipelines in terms of lambdas and collections

2. Lambda Built-in Functional Interfaces

Listing the built-in interfaces included in java.util.function Core interfaces - Predicate, Consumer, Function, Supplier Using primitive versions of base interfaces Using binary versions of base interfaces

3. Lambda Operations

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

4 .Java Date/Time API

Creating and manage date-based events Creating and manage time-based events Combining date and time into a single object Working with dates and times across time zones Managing changes resulting from daylight savings Defining and create timestamps, periods and durations Applying formatting to local and zoned dates and times

5. File I/O (NIO.2)

Using the Path interface to operate on file and directory paths Using the Files class to check, delete, copy, or move a file or directory Using Stream API with NIO2

6. Parallel Streams

Reviewing the key characteristics of streams Describing how to make a stream pipeline execute in parallel List the key assumptions needed to use a parallel pipeline Defining reduction Describing why reduction requires an associative function Calculating a value using reduce Describing the process for decomposing and then merging work Listing the key performance considerations for parallel streams  

Page 4: Java8 training  - Class 1

http://marutsingh.com/

Functional Programming

In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm, which means programming is done with expressions[1] or declarations[2]

 instead of statements. In functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x)each time. Eliminating side effects, i.e. changes in state that do not depend on the function inputs, can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.- Wikipedia

Page 5: Java8 training  - Class 1

http://marutsingh.com/

Basis of functional programming

Function as first class entity Functions with no side-effect

A method, which modifies neither the state of its enclosing class nor the state of any other objects and returns its entire results using return, is called pure or side-effect free.

f(x,y) => x + y Immutability

An immutable object is an object that can’t change its state after it’s instantiated so it can’t be affected by the actions of a function

This means that once immutable objects are instantiated, they can never go into an unexpected state. You can share them without having to copy them, and they’re thread-safe because they can’t be modified

Page 6: Java8 training  - Class 1

http://marutsingh.com/

Collections Streams, and Filters

Page 7: Java8 training  - Class 1

http://marutsingh.com/

Benefits of Functional Programming

Concise code Easy to reason about No side effects Easy to parallelize

Page 8: Java8 training  - Class 1

http://marutsingh.com/

Functional Languages

Haskell Closure Scala OCaml F# Linq Python/Javascript

Page 9: Java8 training  - Class 1

http://marutsingh.com/

Lambda Expression

Lambda expressions define anonymous methods that are treated as instances of functional interfaces.

A lambda expression is composed of parameters, an arrow, and a body.  An arrow— The arrow -> separates the list of parameters from the body of the

lambda.  The body of the lambda— e.g. Compare two objects using their attributes.

The expression is considered the lambda’s return value. As a result lambdas are

it doesn’t have an explicit name like a method would normally have isn’t associated with a particular class like a method is Passed around Concise You don’t need to write a lot of boilerplate like you do for anonymous classes.

Page 10: Java8 training  - Class 1

http://marutsingh.com/

Examples of lambdas

Use case Examples of lambdas

A boolean expression (List<String> list) -> list.isEmpty()

Creating objects () -> new Car()

Consuming from an object (Car a) -> { System.out.println(a.getBrand()); }

Select/extract from an object (String s) -> s.length()

Combine two values (int a, int b) -> a * b

Compare two objects (Car c1, Car c2) -> c1.getWeight().compareTo(c2.getWeight())

Page 11: Java8 training  - Class 1

http://marutsingh.com/

Quiz

Based on the syntax rules just shown, which of the following are not valid lambda expressions? 1. ()->{}2. () -> "Raoul"3. () -> {return "Mario";} 4. (Integer i) -> return "Alan" + i; 5. (String s) -> {"Iron Man";}

Page 12: Java8 training  - Class 1

http://marutsingh.com/

Where to use Lambda?

You can use a lambda expression in the context of a functional interface.

Stream interface exposes many useful methods which take functional interface as an argument. That’s where Lambda can be used

Page 13: Java8 training  - Class 1

http://marutsingh.com/

Iteration Code Demo

public static void printCars(List<Car> carList){ //carList.forEach((Car car) -> car.print()); carList.forEach(car -> { car.print(); });}

Page 14: Java8 training  - Class 1

http://marutsingh.com/

StreamsA sequence of elements supporting sequential and parallel aggregate operations.

Similarities with collections but not collections Do not provide a means to directly access or manipulate their elements, and are

instead concerned with declaratively describing their source and the computational operations which will be performed in aggregate on that source

No storage. A stream is not a data structure that stores elements; instead, it conveys elements from a source such as a data structure, an array, a generator function, or an I/O channel, through a pipeline of computational operations.

Functional in nature. An operation on a stream produces a result, but does not modify its source.

Laziness-seeking. Possibly unbounded. While collections have a finite size, streams need not. Consumable. The elements of a stream are only visited once during the life of a

stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source.

Page 15: Java8 training  - Class 1

http://marutsingh.com/

Streams

Iterating through a collection using lambda syntaxList<Car> carList = new ArrayList<>(); carList.forEach(car -> System.out.println(car));

Stream Interface Filtering

public static void filterByBrand(List<Car> carList,String brand){ carList.stream() .filter(car -> car.getBrand().equalsIgnoreCase(brand)) .forEach(car -> printCar(car));}

Page 16: Java8 training  - Class 1

http://marutsingh.com/

Streams

They support two types of operations: intermediate operations such as filter or map and terminal operations such as count, findFirst, forEach, and reduce.

Intermediate operations can be chained to convert a stream into another stream. These operations don’t consume from a stream; their purpose is to set up a pipeline of streams. By contrast, terminal operations do consume from a stream—to produce a final result (for example, returning the largest element in a stream). They can often shorten computations by optimizing the pipeline of a stream

Page 17: Java8 training  - Class 1

http://marutsingh.com/

Filtering public static void filterCars(List<Car> carList,String brand) {

carList.stream() .filter( car -> car.getBrand().equals(brand)) .forEach(car -> car.print());}

Code Demo

Page 18: Java8 training  - Class 1

http://marutsingh.com/

Method Reference

You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it's often clearer to refer to the existing method by name. Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name.

1. A method reference to a static method (for example, the method parseInt of Integer, written Integer::parseInt)

2. A method reference to an instance method of an arbitrary type (for example, the method length of a String, written String::length)

3. A method reference to an instance method of an existing object

Page 19: Java8 training  - Class 1

http://marutsingh.com/

Functional Interface

A functional interface is an interface that specifies exactly one abstract method.

All functional interfaces have been defined under java.util.function package

@FunctionalInterface public interface Predicate<T>{ boolean test (T t) }; public interface Comparator<T>{ int compaare(T o1,T o2) }; Public interface Callable<V> { V call(); }

Page 20: Java8 training  - Class 1

http://marutsingh.com/

Subtle Mistakes When Using the Streams API

Accidentally re-using StreamIntStream stream = IntStream.of(1, 2);stream.forEach(System.out::println); // That was fun! Let's do it again!stream.forEach(System.out::println);

java.lang.IllegalStateException: stream has already been operated upon or closed

Page 21: Java8 training  - Class 1

http://marutsingh.com/

Subtle Mistakes When Using the Streams API

Accidentally creating infinite streams// Will run indefinitelyIntStream.iterate(0, i -> i + 1)         .forEach(System.out::println);

Page 22: Java8 training  - Class 1

http://marutsingh.com/

Core Interfaces in java.util.function

Predicate Consumer Function Supplier