Java 8

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

JAVA8

Main Objectivies of Java 1.8v


Simplify Java Programming
Enable Functional Programming
Write more readable and concise code
Lists of java 8 features
Functional interface (Predicate,Consumer,Supplier,Function)
Static and default method in interface
Lambda expression
Stream api ( Intermediate and terminal operator/methods)
Method reference
Optional class
Date time api
StringJoiner
forEach ( ) method
Interface changes
Interface means collection of abstract methods
1 ) Default Methods
2 ) Static Methods
Note: The method which doesn't contain body is called as abstract method
A class can implement interface using "implements"
When a class is implementing interface its mandatory that class should
implement all abstract methods of that interface othewise class can't be
compile.
Here i am taking one interface with one abstract method. All the classes
which are implementing that interface should overide interface
method(s).
example
interfaceVehicle{
public abstractvoid startVechicle( );
}
class Car implements Vehicle{
public void startVehicle( ) {
// logic to start car
}}
class Bus implements Vehicle{
public void startVehicle( ) {
// logic to start bus
}}
class Bike implements Vehicle{
public void startVehicle( ) {
// logic to start bike
}}
If we add new method in interfacethen Car, Bike and Bus will fail at compiletime. To overcome above problem we will use Default & Static
methods
1) Interface can have concreate methods from 1.8v
2) Interface concrete method should be default or static
3) interface default methods we can override in impl classes
4) interface static methods we can't overide in impl classes
5) We can write multiple default & static methods in interface
6) Default & Static method introduced to provide backward compatibility.
forEach ( ) method added in java.util.Iterable interface as default method in
1.8v
package in.sbit;
interface Vehicle {
public void start();
public default void m1() { }
public default void m2() { }
public static void clean() {
System.out.println("cleaning completed...");
}}
public class Car implements Vehicle {
public void start() {
System.out.println("car started...");
}
public static void main(String[] args) {
Car c = new Car();
Vehicle.clean();
c.start();
}}
Lambda expression
Introduced in java 1.8v
Java is called as Object Oriented Programming language. Everything will be
represented using Classes and Objects.
From 1.8v onwards Java is also called as Functional Programming Language.
In OOP language Classes & Objects are main entities. We need to write
methods inside the class only.
Functional Programming means everything will be represented in the form
functions. Functions can exist outside of the class. Functions can be stored
into a reference variable. A function can be passed as a parameter to other
methods.
Lambda Expressions introduced in Java to enable Functional Programming.
used to get functionalinterface
more readable, maintanable, concise code
annonyms function(no name, no modifier, no return type)
Lamda expression characterists
it takes any number of parameter
if no parameter in method then it is () optinal
Type interface -> no need to pass datatype to parameter based on
context can gives the type automatically.
What is Lambda ?
Ex:-1
public void m1 ( ) {
s.o.p("hi");
}
( ) -> { s.o.p ("hi") }

Note: When we have single line in body then curly braces are optional
( ) -> s.o.p ("hi");
Ex:-2

public void add (int a, int b){

s.o.p(a+b);

Lambda Expression : (a, b) -> s.o.p(a+b);

Ex:-3

public int getLength (String name) {

return name.length ( );

(String name) -> { return name.length ( ) };

(String name) -> return name.length ( ) ;

(name) -> return name.length ( );

Lambda Expression : name -> name.length ( ) ;


Ex:-4
public Double getEmpSalary (Employee emp) {
return emp.getSalary ( );
}
Lambda Expression : emp -> emp.getSalary ( );
Task : WAJP to print numbers from 1 to 5 using Thread
with the help of Runnable interface.
//using Lambda Expression
public class ThreadDemo3 {
public static void main(String[] args) {
Runnable r = () -> {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
} };
Thread t = new Thread(r);
t.start();
}}
Functional interface
An Interface that contains exactly one abstract method is known as
functional interface.
It can have any number of default, static methods but can contain
only one abstract method.
Functional Interface is also known as Single Abstract Method
Interfaces or SAM Interfaces.
It helps to achieve functional programming approach.
The @FunctionalInterface annotation is optional but can be used
to indicate that the interface is intended for functional
programming.
Usage of Functional Interfaces:
Lambda Expressions:
Functional interfaces are used in conjunction with lambda
expressions to create concise and expressive code.
Method References:
They can be used with method references, providing a shorthand
syntax for lambda expressions.
Stream API:
Functional interfaces are commonly used with the Stream API for
processing collections of data in a functional style.
=========================================================
Predicate ------> takes inputs ----> returns true or false ===> test ( )
Supplier -----> will not take any input---> returns output ===> get ( )
Consumer ----> will take input ----> will not return anything ===>
accept ( )
Function -----> will take input ---> will return output ===> apply ( )
Runnable ------------> run ( ) method
Callable ----------> call ( ) method
Comparable -------> compareTo( )
To represent one interface as Functional Interface we will use
@FunctionalInterface annotation.
@FunctionalInterface
public interface MyInterface {
public void m1( );
}
Note: When we write @FunctionalInterface then our compiler will check interface
contains only one abstract method or not.
Predicate Functional Interface
It is predefined Functional interface
It is used check condition and returns true or false value
Predicate interface having only one abstract method that is test (T t)
interface Predicate{
boolean test(T t);
}
Predicate Example
// Predicate Example
package in.sb.java8;
import java.util.function.Predicate;
public class PredicateDemo {
public static void main(String[] args) {
Predicate<Integer> p = i -> i > 10;
System.out.println(p.test(5));
System.out.println(p.test(15));
}
}
Example
Task: Declare names in an array and print names which are starting with 'A' using lambda expression.
String[ ] names = {"Anushka", "Anupama", "Deepika", "Kajol", "Sunny" };
package in.sb.java8;
import java.util.function.Predicate;
public class PredicateDemo2 {
public static void main(String[] args) {
String[ ] names = { "Anushka", "Anupama", "Deepika", "Kajol", "Sunny" };
Predicate<String> p = name -> name.charAt(0) == 'A';
for (String name : names) {
if ( p.test(name) ) {
System.out.println(name);
} } }}
Supplier Functional Interface

Supplier -
Supplier is a predefined functional interface introduced in java 1.8v
It contains only one abstract method that is get ( ) method
Supplier interface will not take any input, it will only returns the
value.

Example : OTP Generation


Supplier Example
package in.sbit.java8;
import java.util.function.Supplier;
public class SupplierDemo {
public static void main(String[] args) {
Supplier<String> s = () -> {
String otp = "";
for (int i = 1; i <= 6; i++) {
otp = otp + (int) (Math.random() * 10);
}
return otp;
};
System.out.println(s.get());
System.out.println(s.get());
System.out.println(s.get());
}}
Consumer Functional Interface
Note: in java 8 forEach ( ) method got introduced.
forEach(Consumer consumer) method will take Consumer as parameter.
package in.sbt.java8;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ConsumerDemo {
public static void main(String[] args) {
Consumer<String> c = (name) -> System.out.println(name + ", Good Evening");
c.accept("Ashok");
c.accept("John");
c.accept("Rani");
List<Integer> numbers = Arrays.asList(10, 20, 30, 40);
// for loop
// for each loop
// iterator
// list iterator
numbers.forEach(i -> System.out.println(i));
} }
Function Functional Interface
Function is predefined functional interface
Funcation interface having one abstract method i.e apply(T r)
Example :
interface Function<R,T>{
R apply (T t);
}
It takes input and it returns output
package in.java8;
import java.util.function.Function;
public class FunctionDemo {
public static void main(String[] args) {
Function<String, Integer> f = (name) -> name.length();
System.out.println(f.apply("ashok"));
System.out.println(f.apply("hyd"));
System.out.println(f.apply("sachin"));
}}
Method References
Method reference means Reference to one method from another method.

Example :
@FunctionalInterface
interface MyInterface {
publicvoid m1();
}
public class MethodRef {
public static void m2() {
System.out.println("This is m2( ) method");
}
public static void main(String[] args) {
MyInterface mi = MethodRef::m2;
mi.m1();
}}
//Doctor class creating object

public class Test {

public static void main(String[] args) {

// Doctor d = new Doctor();

Supplier<Doctor> s = Doctor::new;

Doctor doctor = s.get();

System.out.println(doctor.hashCode());

}}

class Doctor {

public Doctor() {

System.out.println("Doctor constructor....");

}}
Stream api
Stream API introduced in java 1.8v
Stream API is used to process the data
Note: Collections are used to store the data
Stream API is one of the major features added in java 1.8v
Stream in java can be defined as sequence of elements that comes from
a source.
Source of data for the Stream can be array or collection.
Few Important Points About Streams
Stream is not a data structure. Stream means bunch of operations
applied on source data. Source can be collection or array.
Stream will not change original data structure of the source (It will just
process the data given by the source.
Stream Creation
In Java we can create Stream in 2 ways
1) Stream.of (e1, e2, e3, e4.....)
2) stream ( ) method
Stream Operations
Stream API provided several methods to perform Operations on the data
We can divide Stream api methods into 2 types
1) Intermediate Operational Methods
2) TerminalOperational Methods
Intermediate Operational methods will perform operations on the
stream and returns a new Stream
Ex: filter ( ) , map ( ) etc....
TerminalOperational methods will take input and will provide result as
output.
Ex: count ( )
Filtering with Streams
Filtering means getting required data from original data
Ex: get only even numbers from given numbers
Ex: get emps whose salary is >= 1,00,000
Ex: Get Mobiles whose price is <= 15,000
To apply filter on the data, Stream api provided filter ( ) method
Ex : Stream filter (Predicate p)
Example - 1 : Filter
package in.ashokit.streams;
importjava.util.Arrays;
importjava.util.List;
public class FirstDemo {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(66, 32, 45, 12, 20);
/*for (Integer i : list) {
if (i > 20) {
System.out.println(i);
} }*/
/* Stream<Integer> stream = list.stream();
Stream<Integer>filteredStrem = stream.filter(i -> i > 20);
filteredStrem.forEach(i -> System.out.println(i)); */
list.stream().filter(i -> i > 20).forEach(i -> System.out.println(i));
}}
Mapping Operations
Mapping operations are belongs to intermediate operations in the Stream api
Mapping operations are used to transform the stream elements and return transformed
elements as new Stream
Ex : Stream map (Function function) ;
public class FirstDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList("india","usa","uk", "japan");
/*for(String name : names) {
System.out.println(name.toUpperCase());
}*/
names.stream().map(name -> name.toUpperCase()).forEach(n -> System.out.println(n));
names.stream().mapToInt(name -> name.length()).forEach(i -> System.out.println(i));
}}
Example-2 : map ( ) method
public class FirstDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList("Ashok", "Anil", "Raju", "Rani", "John", "Akash", "Charles");
// print name with its length which are starting with 'A' using Stream API
//Ashok - 5
//Anil - 4
//Akash - 5
names.stream()
.filter(name -> name.startsWith("A"))
.map(name -> name + "-" +name.length())
.forEach(name -> System.out.println(name));
}
}
Collectors with Stream
Collectors are used to collect data from Stream.
Example :
class Person {
String name;
String country;
public Person(String name, String country) {
this.name = name;
this.country = country;
}
@Override
public StringtoString() {
return "Person [name=" + name + ", country=" + country + "]";
}}
package in.asit.streams;
importjava.util.Arrays;
importjava.util.List;
importjava.util.stream.Collectors;
public class FirstDemo {
public static void main(String[] args) {
Person p1 = new Person("John", "USA");
Person p2 = new Person("Steve", "JAPAN");
Person p3 = new Person("Ashok", "INDIA");
Person p4 = new Person("Ching", "CHINA");
Person p5 = new Person("Kumar", "INDIA");
List<Person> persons = Arrays.asList(p1, p2, p3, p4, p5);
List<Person> indians = persons.stream() .filter(p -> p.country.equals("INDIA"))
.collect(Collectors.toList());
indians.forEach(i -> System.out.println(i));
}}
List<Person> persons = Arrays.asList(p1, p2, p3, p4, p5);
// collect names of persons who are belongs to india and store into
names collection
List<String> names = persons.stream()
.filter(p -> p.country.equals("INDIA"))
.map(p -> p.name)
.collect(Collectors.toList());
System.out.println(names);
Set - 1 : Intermediate Operations (will return Stream)
Filters ----> filter ( )
Mappings ----> map ( ) & flatMap ( )
Slicing ----> distinct ( ) & limit () & skip ( )

Set - 2 : TerminalOperations (will return result)


Finding ---> findFirst ( ) & findAny ( )
Matching ---> anyMatch ( ) & allMatch ( ) & noneMatch ( )
Collecting ---> collect ( )
Optional Class
java.util.Optional class introduced in java 1.8v
Optional class is used to avoid NullPointerExceptions in the program
Q) What is NullPointerException (NPE) ?
Ans) When we perform some operation on null value then we will get
NullPointerException
String s = null;
s.length ( ) ; // NPE (null pointer exception )
To avoid NullPointerExceptions we have to implement null check before performing
operation on the Object like below.
String s = null;
if( s! = null ) {
System.out.println(s.length ( ));
}
Note: In project there is no gaurantee that every programmer will implement null checks. If
any body forgot to implement null check then program will run into NullPointerException.
To avoid this problem we need to use Optional class like below.
Example
package in.asit.java8;
import java.util.Optional;
import java.util.Scanner;
public class MsgService {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter User ID");
int userId = s.nextInt();
User u = new User();
/*String userName = u.getUsernameById(userId);
String msg = userName.toUpperCase() + ", Hello";
System.out.println(msg);*/
Optional<String> username = u.getUsername(userId);
if(username.isPresent()) {
String name = username.get();
System.out.println(name.toUpperCase()+", Hello");
}else {
System.out.println("No Data Found");
} }}
Date & Time API
In java we have below 2 classes to represent Date
1) java.util.Date
2) java.sql.Date
Note: When we are performing database operations then we will use java.sql.Date
class.
For normal Date related operations we will use java.util.Date class
Date d = new Date ( );
System.out.prinln(d);
Note: When we create Object for Date class, it will represent both date and time.
If we want to get only date or only time then we need to format it using
SimpleDateFormat class.
java.text.SimpleDateFormat
SimpleDateFormat is a predefined class in java.text pacakage
This class provided methods to perform Date conversions
Date to String conversion ===> String format (Date d)
String to Date conversion ===> Date parse(String str)
import java.time.*;
import java.time.format.DateTimeFormatter;

public class Date {


public static void LocalDateTimeApi() {
LocalDate date = LocalDate.now(); // the current date
System.out. println("the current date is "+ date);

LocalTime time = LocalTime.now(); // the current time


System.out.println("the current time is "+ time);

LocalDateTime current = LocalDateTime.now(); // will give us the current time and date
System.out.println("current date and time : "+ current);

DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); // to print in a particular format


String formatedDateTime = current.format(format);
System.out.println("in formatted manner "+ formatedDateTime);

LocalDate date2 = LocalDate.of(1950,1,26); // printing some specified date


System.out.println("the republic day :"+date2);

LocalDateTime specificDate = current.withDayOfMonth(24).withYear(2016); // printing date with current time.


System.out.println("specific date with "+ "current time : "+specificDate);
}

public static void main(String[] args) // Driver code {


LocalDateTimeApi();
}}
Date Conversions Example
package in.ashokit.java8;
importjava.text.SimpleDateFormat;
importjava.util.Date;
public class DateDemo {
public static void main(String[] args) throws Exception {
Date date = new Date();
System.out.println(date);
// Converting Date to String
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
Stringformat1 = sdf1.format(date);
System.out.println(format1);
SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd/yyyy");
Stringformat2 = sdf2.format(date);
System.out.println(format2);
// Convert Stringto Date
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDate = sdf3.parse("2022-12-20");
System.out.println(parsedDate);
}
}
To overcome the problems of java.util.Date class java 1.8
introduced Date API changes
LocalDate
14.2) LocalTime
14.3) LocalDateTime
14.4) Period
14.5) Duration

In java 1.8 versions, new classes got introduced to deal with Date &
Time functionalities
1) java.time.LocalDate (it will deal with only date)
2) java.time.LocalTime (it will deal with only time) 3)
java.time.LocalDateTime (it will deal with both date & time)
forEach (Consumer c) method
forEach (Consumer c) method introduced in java 1.8v
forEach ( ) method added in Iterable interface
forEach ( ) method is a default method (it is having body)
This is method is used to access each element of the collection
(traverse collection from start to end)
Example :
package in.sbit.java8;
import java.util.ArrayList;
public class NumbersSort1 {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
al.add(3);
al.add(4);
al.add(1);
al.add(2);
al.forEach(i -> System.out.println(i));
}}
StringJoiner
java.util.StringJoiner class introduced in java 1.8v
It is used to join more than one String with specified delimiter
We can concat prefix and suffix while joininging strings using
StringJoiner
StringJoiner sj = new StringJoiner (CharSequence delim);
StringJoiner sj = new StringJoiner (CharSequence delim, CharSequence
prefix, CharSequence suffix);
Example :
package in.sb.java8;
importjava.util.StringJoiner;
public class StringJoinerDemo {
public static void main(String[] args) {
StringJoiner sj1 = new StringJoiner("-");
sj1.add("as");
sj1.add("it");
sj1.add("java");
System.out.println(sj1); // as-it-java
StringJoiner sj2 = new StringJoiner("-", "(", ")");
sj2.add("as");
sj2.add("it");
sj2.add("java");
System.out.println(sj2); // (as-it-java)
}}

You might also like