Java 8
Java 8
@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.
• 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
For Example: is a fixed data set.
List -> list.add(<element>)
Elements in the collection can be accessed in any Elements in the Stream can be accessed only in
order. Use appropriate methods based on the sequence.
collection.
For Example:
List -> list.get(4);
Collections Streams
Collections can be traversed “n” number of Streams can be traversed only once.
times.
Performs External Iteration to iterate through Performs Internal Iteration to iterate through the
the elements. elements.
Stream API : map()
• map : Convert(transform) one type to another.
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()
• 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.