Modern Java v2
Modern Java v2
• Dilip
• Functional Programming, Lambdas, Streams, Optionals, New Date/Time APIs and more.
• Local Variable Type Inference (LVTI), Record Types, Enhanced Switch, TextBlocks, Sealed
Classes, Pattern Matching, JPMS and more.
• This course will be continuously updated with all the new features.
• Git
Java
Programming
Language
Java
Java Platform
[ JDK -> JRE + JVM ]
Evolution of Java = Modern Java
• Functional Programming (Java 8)
• Lambdas, Streams
• CompletableFuture
• Release of Java Modules (Java 9)
• Java Platform Module System
• Java Runtime Libraries are also modularized.
• Six Month Release Cycle(Java 10 onwards)
• Release new features every 6 months
Java 8 Java 9 & Beyond
• Lambdas • Java Platform Module System (JPMS)
• Local Variable Type Inference (LVTI)
• Streams
• Record Types
• Optionals • Enhanced Switch
• TextBlocks
• New Date/Time APIs • Sealed Classes
• Pattern Matching
• Virtual Threads
Java 8 Java 9 & Beyond
• Lambdas • Java Platform Module System
(JPMS)
• Streams • Local Variable Type Inference (LVTI)
• Record Types
• Optionals
• Enhanced Switch
• New Date/Time APIs • TextBlocks
• Sealed Classes
• Pattern Matching
Java Release Model
• Java is an open source language and its managed under the OpenJDK project.
• Java 7 was the rst version that was relesed under the open source license.
• OpenJDK project is manitained by Oracle, Redhat and the community.
• There are di erent OpenJDK providers:
• Orcale, Eclipse Adoptium(Temurin) , Amazon(Corretto), Azul Systems (Zulu),
IBM, Microsoft, Red Hat, and SAP
• All of these vendors have this concept of LTS (Long Term Support) releases.
• Primary applications run on these LTS releases even though new Java
version is released every 6 months
ff
fi
Why Java 8 ?
• Most popular and widely accepted language in the world.
• Use the functions that are already part of the library to achieve an objective.
Example 1
Sum of 100 numbers from 0 to 100
Imperative vs Declarative Programming
Example 2
Removing duplicates from a list of integers
What is Lambda Expression?
Lambda Expression:
( ) -> { }
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
}
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
Lets code our first Lambda!
Implement Runnable using Lambda
Lambda in Practice ( Things to keep in Mind)
Java 8:
Runnable runnableLambda = () -> {System.out.println("Inside Runnable 2");};
Functional Interfaces
Definition:
• A Functional Interface(SAM) is an interface that has exactly one abstract method.
@FunctionalInterface:
• This annotation is introduced as part of the JDK 1.8.
• Predicate
• Function
• Supplier
New Functional Interfaces in Java8
• Consumer – BiConsumer
• Predicate - BiPredicate
• Supplier
New Functional Interfaces in Java8
• Consumer – IntConsumer, DoubleConsumer, LongConsumer
ClassName::instance-methodName
ClassName::static-methodName
Instance::methodName
Where to use Method Reference?
• Lambda expressions referring to a method directly.
Using Lambda:
Function<String,String> toUpperCaseLambda = (s)->s.toUpperCase();
Example:
Predicate<Student> predicateUsingLambda = (s) -> s.getGradeLevel()>=3;
Constructor Reference
• Introduced as part of Java 1.8
Syntax:
Classname::new
Example:
Supplier<Student> studentSupplier = Student::new;
Invalid:
Student student = Student::new; // compilation issue
Lambdas and Local Variables
What is a Local variable ?
• Any variable that is declared inside a method is called a local variable.
• Prior to Java 8 , any variable that’s used inside the anonymous class should
be declared final.
Advantages of Effectively Final:
• Streams API can be also used with arrays or any kind of I/O .
What is a Stream ?
• Stream is a sequence of elements which can be created out of a
collections such as List or Arrays or any kind of I/O resources and etc.,
Collections Streams
Can add or modify elements at any point of time. Cannot add or modify elements in the stream. It is a
For Example: data set.
List -> list.add(<element>)
Elements in the collection can be accessed in any order. Elements in the Stream can be accessed only in
Use appropriate methods based on the collection. sequence.
For Example:
List -> list.get(4);
Collections Streams
Collections can be traversed “n” number of times. Streams can be traversed only once.
Performs External Iteration to iterate through the Performs Internal Iteration to iterate through the
elements. elements.
Stream API : map()
• map : Convert(transform) one type to another.
• anyMatch()- Returns true if any one of the element matches the predicate,
otherwise false.
• allMatch() - Returns true if all the element in the stream matches the predicate,
otherwise false.
• noneMatch() – Just opposite to allMatch(). Returns true if none of the element
in the stream matches the predicate, otherwise false.
Streams API : findFirst() and findAny()
• Used to find an element in the stream.
anyMatch()
findFirst()
limit() allMatch()
findAny()
noneMatch()
• All these functions does not have to iterate the whole stream to
evaluate the result.
Streams API : Stateful vs Stateless
• Does Streams have an internal state?
• Yes
• Does all the Stream functions maintain an internal state ?
• No
What is a State in Streams API ?
Converts a List<Student> to List<String>
private static List<String> namesUpperCase(List<Student> names){
List<String> namesUpperCase = names.stream()
.map(Student::getName)
.map(String::toUpperCase) (Stream State) (Stream Pipeline)
.collect(toList());
return namesUpperCase;
}
Intermediate Operations
• Stateful functions
• distinct()
• sorted()
• skip()
• limit()
• Stateless functions
• map()
• filter(), etc.,
Stateful functions:
Example:
Stream.generate(<Supplier>)
Numeric Streams
Represents the primitive values in a Stream.
• IntStream
• LongStream
• DoubleStream
Numeric Stream Ranges:
Int Stream:
IntStream.range(1,50) -> Returns an IntStream of 49 elements from 1 to 49.
IntStream.rangeClosed(1,50) -> Returns an IntStream of 50 elements from 1 to
50.
Long Stream:
LongStream.range(1,50) -> Returns a LongStream of 49 elements from 1 to 49.
LongStream.rangeClosed(1,50) -> Returns a LongStream of 50 elements from 1
to 50.
DoubleStream:
- It does not support the range ()and rangeClosed().
Numeric Stream – Aggregate Functions
• sum()
• max()
• min()
• average()
Numeric Streams : Boxing() and UnBoxing()
Boxing():
• Converting a primitive type to Wrapper Class type
Example:
• Converting an int (primitive) to Integer(wrapper).
UnBoxing():
• Converting a Wrapper Class type to primitive type.
Example:
• Converting an Integer(wrapper) to int(primitive).
Numeric Streams – mapToObj(), mapToLong(),
mapToDouble()
• Terminal Operations:
• forEach()
• min()
• max()
• reduce()
• collect() and etc.
Terminal Operation – collect()
• Produces the result as per the input passed to the collect() method.
Terminal Operations – joining()
• minBy()
• This collector is used in conjunction with comparator. Returns the smallest
element based on the property passed to the comparator.
Terminal Operations – summingInt(), averagingInt()
Parallel Stream:
IntStream.rangeClosed(1,1000)
.parallel()
.sum();
How Parallel Stream works ?
• Parallel Stream uses the Fork/Join framework that got introduced in
Java 7.
• A class can extend only one class but a class can implement multiple
interfaces.
Does this enable Multiple Inheritance in
Java?
• Yes
• These new classes are created with the inspiration from the Joda-Time library.
Example:
Period period1 = Period.ofDays(10); // represents a Period of 10 days
Period period2 = Period.ofYears(20); // represents a Period of 20 years
Period : Use-Case
• Mainly used calculate the difference between the two dates.
Example:
LocalDate localDate = LocalDate.of(2018,01,01);
LocalDate localDate1 = LocalDate.of(2018,01,31);
Period period = Period.between(localDate,localDate1); // calculates the difference between the two
dates
Duration
• A time based representation of time in hours , minutes,
seconds and nanoseconds.
• Compatible with LocalTime and LocalDateTime
• It represents a duration of time not just a specific time.
Example:
Duration duration1 = Duration.ofHours(3);; // represents the duration of 3 hours
Duration duration1 = Duration. ofMinutes(3); // represents the duration of 3 minutes
Duration : Use-Case
• It can be used to calculate the difference between the time objects
such as LocalTime and LocalDateTime.
Example:
LocalTime localTime = LocalTime.of(7,20);
LocalTime localTime1 = LocalTime.of(8,20);
Duration duration = Duration.between(localTime,localTime1);
Instant:
• Represent the time in a machine readable format.
Example:
Instant ins = Instant.now();
ZoneOffset-> -05:00
ZoneId -> America/Chicago
DateTimeFormatter
• Introduced in Java 8 and part of the java.time.format package.
Variable name
Reserved type
name
fi
Local Variable Type Inference( LVTI ) using “var”
Inlay hints
Limitations of using “var”
• “null” value cannot be assigned to a “var” as the type cannot be inferred.
• var x = null
• Changing the type is not allowed.
var s = "Hello, World”;
• Sql: • JSON:
var json = """
var sql = """ {
SELECT * FROM employee "order_id": 123456,
WHERE first_name = 'Dilip' "status": "DELIVERED",
AND last_name = 'Sundarraj' "final_charge": 999.99,
"""; "order_line_items": [{
"item_name": "iphone 14",
"quantity": 1
}]
}
"""
;
Enhanced Switch
• Enhanced Switch got released as part of Java 14.
• Enhanced Switch is an “expression”.
• The switch statement returns a value.
Enhanced Switch
• Function that returns the number of days based on the Month and Year.
ff
Sealed Classes/Interfaces
• This concept was generally available from Java 17.
• Allow inheritance by permission.
public final class Car extends Vehicle { } public final class Truck extends Vehicle{ }
• This ensures that inheritance is allowed but controlled for classes thats
de ned after the permits keyword.
• In this case, any class can extend the subclass Car. This basically disables
the controlled inheritance behavior.
fi
fi
Why Pattern Matching?
• Code is verbose.
• Step 1 and Step 2 can be combined public String pattern(Object o) {
if (o instanceof Integer) { 1 Check the type
into one step. cast and create a 2 var i = (Integer) o;
variable return "Integer:" + i; 3 Act on the variable
}
if (o instanceof String) {
var i = (String) o;
return "String of length:" + i.length();
}
return "Not a String or Integer";
return "Integer:" + I; 2
Type Patterns. }
• Other Patterns:
• Record Patterns
• Guarded Patterns
Pattern Matching - Different Approaches
}
• Each case statement applies a pattern match.
Checkout Payment
Service Service
orderDetails
3
Factory class to retrieve the appropriate PaymentGateway.
• The Client has the support for build clients in both Synchronous and
Asynchronous mode.
Java Platform Module System (JPMS) or Project Jigsaw
• This is a new concept that got introduced in Java 9.
• Why JPMS ?
• New restrictive controls are available to restrict access to certain internal classes.
• Eg., We can control the packages in a library that can exposed to the client(library
user).
• In today’s words, any class can be accessed and modi ed using Re ection.