SlideShare a Scribd company logo
1 of 166
Download to read offline
Modern Programming in Java 8
Lambdas, Streams and Date/Time API
GANESH & HARI
CODEOPS TECHNOLOGIES
ganesh@codeops.tech
hari@codeops.tech
Adapt: Learn functional
programming
Agenda
• Introduction & Overview
• Lambdas
• Functional interfaces
• Streams
• Parallel Streams
• Date & Time package
• Refactoring to Java 8
Java meets functional
programming (with lambdas)
Java is not your grandma’s
language anymore!
Greek characters
are scary!
He he, but lambdas
are fun, not scary
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
Consumer<String> printString = string -> System.out.println(string);
strings.forEach(printString);
Lambda
functions!
But what are
lambdas?
Lambdas is just a fancy
name for functions
without a name!
What are lambda functions?
❖ (Java 8) One way to think about lambdas is
“anonymous function” or “unnamed function” - they
are functions without a name and are not associated
with any class
❖ They don’t change external state
What is functional programming?
❖ Functional languages view programs as an entity—
called a function—that accepts inputs and produces
output
❖ Functions are connected together by their outputs to
other functions’ inputs
❖ Underlying approach: “Evaluate an expression. Then
use the results for something else.”
Perspective - for loops!
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
for(String string : strings) {
System.out.println(string);
}
External Iteration
Perspective - for loops!
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
strings.forEach(string -> System.out.println(string));
Internal Iteration
Perspective - for loops!
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
strings.forEach(string -> System.out.println(string));
Internal Iteration
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
for(String string : strings) {
System.out.println(string);
}
External Iteration
Perspective - for loops!
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
strings.forEach(string -> System.out.println(string));
Internal Iteration
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
for(String string : strings) {
System.out.println(string);
}
External Iteration
Procedural
thinking
Functional
thinking
You can use lambdas for
some amazing stuff
sedime
nt
pre-
carbon
ultra-
filter
post-
carbon
Filtered
water
E.g., you can compose lambda
functions as in pipes-and-filters
$ cat limerick.txt
There was a young lady of Niger
Who smiled as she rode on a tiger.
They returned from the ride
With the lady inside
And a smile on the face of the tiger.
$ cat limerick.txt | tr -cs "[:alpha:]" "n" | awk '{print length(), $0}' | sort | uniq
1 a
2 as
2 of
2 on
3 And
3 Who
3 she
3 the
3 was
4 They
4 With
4 face
4 from
4 lady
4 ride
4 rode
5 Niger
5 There
5 smile
5 tiger
5 young
6 inside
6 smiled
8 returned
List<String> lines
= Files.readAllLines(Paths.get("./limerick.txt"), Charset.defaultCharset());
	 	 Map<Integer, List<String>> wordGroups
	 	 = lines.stream()
	 .map(line -> line.replaceAll("W", "n").split("n"))
	 .flatMap(Arrays::stream)
	 .sorted()
	 .distinct()
	 .collect(Collectors.groupingBy(String::length));
	 	 wordGroups.forEach( (count, words) -> {
	 	 words.forEach(word -> System.out.printf("%d %s %n", count, word));
	 	 });
1 a
2 as
2 of
2 on
3 And
3 Who
3 she
3 the
3 was
4 They
4 With
4 face
4 from
4 lady
4 ride
4 rode
5 Niger
5 There
5 smile
5 tiger
5 young
6 inside
6 smiled
8 returned
Lambdas & streams help in
productive programming!
public static void main(String []file) throws Exception {
// process each file passed as argument
// try opening the file with FileReader
try (FileReader inputFile = new FileReader(file[0])) {
int ch = 0;
while( (ch = inputFile.read()) != -1) {
// ch is of type int - convert it back to char
System.out.print( (char)ch );
}
}
// try-with-resources will automatically release FileReader object
}
public static void main(String []file) throws Exception {
Files.lines(Paths.get(file[0])).forEach(System.out::println);
}
Existing APIs are enriched with
lambdas and streams support
Java 8 is the new Groovy ;-)
import	java.io.*;	
class	Type	{	
	 public	sta7c	void	main(String	[]files)	{	
	 	 //	process	each	file	passed	as	argument		
	 	 for(String	file	:	files)	{	
	 	 	 //	try	opening	the	file	with	FileReader		
	 	 	 try	(FileReader	inputFile	=	new	FileReader(file))	{		
	 	 	 	 int	ch	=	0;		
	 	 	 	 while(	(ch	=	inputFile.read())	!=	-1)	{	
	 	 	 	 	 //	ch	is	of	type	int	-	convert	it	back	to	char	
	 	 	 	 	 System.out.print(	(char)ch	);		
	 	 	 	 }	
	 	 	 }	catch	(FileNotFoundExcep7on	fnfe)	{	
	 	 	 	 System.err.prinR("Cannot	open	the	given	file	%s	",	file);	
	 	 	 }	
	 	 	 catch(IOExcep7on	ioe)	{	
	 	 	 	 System.err.prinR("Error	when	processing	file	%s;	skipping	it",	file);	
	 	 	 }		
	 	 	 //	try-with-resources	will	automa7cally	release	FileReader	object			
	 	 }	
	 }	
}	
args.each	{	println	new	File(it).getText()	}
Agenda
• Introduction & Overview
• Lambdas
• Functional interfaces
• Streams
• Parallel streams
• Date & Time package
• Refactoring to Java 8
Java 8 lambdas - “Hello world!”
interface LambdaFunction {
void call();
}
class FirstLambda {
public static void main(String []args) {
LambdaFunction lambdaFunction = () -> System.out.println("Hello world");
lambdaFunction.call();
}
}
Java 8 lambdas - “Hello world!”
interface LambdaFunction {
void call();
}
class FirstLambda {
public static void main(String []args) {
LambdaFunction lambdaFunction = () -> System.out.println("Hello world");
lambdaFunction.call();
}
}
Functional interface - provides
signature for lambda functions
Lambda function/expression
Call to the lambda
Prints “Hello world” on the console when executed
Parts of a lambda expression
() -> System.out.println("Hello world");
No parameters, i.e., ()
Arrow operator that separates
parameters and the body
The lambda body
Return type “void” inferred from the body
Method references
Method references - “syntactic sugar” for lambda
functions
They “route” function parameters
arg -> System.out.println(arg)
System.out::println
Method references
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
Consumer<String> printString = System.out::println;
strings.forEach(printString);
Method
reference
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
Consumer<String> printString = string -> System.out.println(string);
strings.forEach(printString);
Method references
Cannot use method references when lambda functions do
more than“routing” function parameters
strings.forEach(string -> System.out.println(string.toUpperCase()));
More processing here than just
“routing” parameters
Method references
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
Consumer<String> printString = System.out::println;
strings.forEach(printString);
public static void printUpperCaseString(String string) {
System.out.println(string.toUpperCase());
}
strings.forEach(MethodReference::printUpperCaseString);
“Effectively final” variables
import java.util.Arrays;
import java.util.List;
class PigLatin {
public static void main(String []args) {
String suffix = "ay";
List<String> strings = Arrays.asList("one", "two", "three", "four");
strings.forEach(string -> System.out.println(string + suffix));
}
} Accessing “local variable” suffix
here; hence it is considered
“effectively final”
“Effectively final” variables
import java.util.Arrays;
import java.util.List;
class PigLatin {
public static void main(String []args) {
String suffix = "ay";
List<String> strings = Arrays.asList("one", "two", "three", “four");
suffix = "e"; // assign to suffix variable
strings.forEach(string -> System.out.println(string + suffix));
}
}
PigLatinAssign.java:9: error: local variables referenced from a
lambda expression must be final or effectively final
strings.forEach(string -> System.out.println(string + suffix));
^
1 error
Agenda
• Introduction & Overview
• Lambdas
• Functional interfaces
• Streams
• Parallel streams
• Date & Time package
• Refactoring to Java 8
Functional interfaces
@FunctionalInterface
interface LambdaFunction {
void call();
}
Functional interface
Abstract method providing the signature of the
lambda function
Annotation to explicitly state that it is a functional
interface
Java 8 lambdas - “Hello world!”
@FunctionalInterface
interface LambdaFunction {
void call();
}
class FirstLambda {
public static void main(String []args) {
LambdaFunction lambdaFunction = () -> System.out.println("Hello world");
lambdaFunction.call();
}
}
Functional interface - provides
signature for lambda functions
Lambda function/expression
Call to the lambda
Prints “Hello world” on the console when executed
Older Single Abstract Methods (SAMs)
// in java.lang package
interface Runnable { void run(); }
// in java.util package
interface Comparator<T> { boolean compare(T x, T y); }
// java.awt.event package:
interface ActionListener { void actionPerformed(ActionEvent e) }
// java.io package
interface FileFilter { boolean accept(File pathName); }
Functional interfaces: Single abstract methods
@FunctionalInterface
interface LambdaFunction {
void call();
// Single Abstract Method (SAM)
}
Using built-in functional interfaces
// within Iterable interface
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
// in java.util.function package
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
// the default andThen method elided
}
Using built-in functional interfaces
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
Consumer<String> printString = string -> System.out.println(string);
strings.forEach(printString);
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
strings.forEach(string -> System.out.println(string));
Default methods in interfaces
public interface Iterator<E> {
boolean hasNext();
E next();
default void remove() {
throw new UnsupportedOperationException("remove");
}
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
}
“Diamond” inheritance problem?
“Diamond” inheritance problem?
interface Interface1 {
default public void foo() { System.out.println("Interface1’s foo"); }
}
interface Interface2 {
default public void foo() { System.out.println("Interface2’s foo"); }
}
public class Diamond implements Interface1, Interface2 {
public static void main(String []args) {
new Diamond().foo();
}
}
Error:(9, 8) java: class Diamond inherits unrelated defaults for foo()
from types Interface1 and Interface2
“Diamond” inheritance problem?
interface Interface1 {
default public void foo() { System.out.println("Interface1’s foo"); }
}
interface Interface2 {
default public void foo() { System.out.println("Interface2’s foo"); }
}
public class Diamond implements Interface1, Interface2 {
public void foo() { Interface1.super.foo(); }
public static void main(String []args) {
new Diamond().foo();
}
}
Add this definition
to resolve the
ambiguity
“Diamond” inheritance problem?
class BaseClass {
public void foo() { System.out.println("BaseClass’s foo"); }
}
interface BaseInterface {
default public void foo() { System.out.println("BaseInterface’s foo”); }
}
public class Diamond extends BaseClass implements BaseInterface {
public static void main(String []args) {
new Diamond().foo();
}
}
Compiles cleanly; Java 8
rules help deal with the
diamond problem
Built-in functional interfaces
Built-in functional interfaces are a
part of the java.util.function
package (in Java 8)
Built-in interfaces
Predicate<T> Checks a condition and returns a
boolean value as result
In filter() method in
java.util.stream.Stream
which is used to remove elements
in the stream that don’t match the
given condition (i.e., predicate) asConsumer<T> Operation that takes an argument but
returns nothing
In forEach() method in
collections and in
java.util.stream.Stream; this
method is used for traversing all
the elements in the collection orFunction<T,
R>
Functions that take an argument and
return a result
In map() method in
java.util.stream.Stream to
transform or operate on the passed
value and return a result.
Supplier<T> Operation that returns a value to the
caller (the returned value could be
same or different values)
In generate() method in
java.util.stream.Stream to
create a infinite stream of
elements.
Predicate interface
Stream.of("hello", "world")
.filter(str -> str.startsWith("h"))
.forEach(System.out::println);
The filter() method takes a Predicate
as an argument (predicates are
functions that check a condition and
return a boolean value)
Predicate interface
Predicate interface
A Predicate<T> “affirms” something as true or
false: it takes an argument of type T, and returns a
boolean value. You can call test() method on a
Predicate object.
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
// other methods elided
}
Predicate interface: Example
import java.util.function.Predicate;
public class PredicateTest {
public static void main(String []args) {
Predicate<String> nullCheck = arg -> arg != null;
Predicate<String> emptyCheck = arg -> arg.length() > 0;
Predicate<String> nullAndEmptyCheck = nullCheck.and(emptyCheck);
String helloStr = "hello";
System.out.println(nullAndEmptyCheck.test(helloStr));
String nullStr = null;
System.out.println(nullAndEmptyCheck.test(nullStr));
}
}
Prints:
true
false
Predicate interface: Example
import java.util.List;
import java.util.ArrayList;
public class RemoveIfMethod {
public static void main(String []args) {
List<String> greeting = new ArrayList<>();
greeting.add("hello");
greeting.add("world");
greeting.removeIf(str -> !str.startsWith("h"));
greeting.forEach(System.out::println);
}
}
Prints:
hello
Consumer interface
Stream.of("hello", "world")
.forEach(System.out::println);
// void forEach(Consumer<? super T> action);
Prints:
hello
world
Consumer interface
Consumer interface
A Consumer<T> “consumes” something: it takes
an argument (of generic type T) and returns
nothing (void). You can call accept() method on a
Consumer object.
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
// the default andThen method elided
}
Consumer interface: Example
Consumer<String> printUpperCase =
str -> System.out.println(str.toUpperCase());
printUpperCase.accept("hello");
Prints:
HELLO
Consumer interface: Example
import java.util.stream.Stream;
import java.util.function.Consumer;
class ConsumerUse {
public static void main(String []args) {
Stream<String> strings = Stream.of("hello", "world");
Consumer<String> printString = System.out::println;
strings.forEach(printString);
}
}
Prints:
hello
world
Function interface
import java.util.Arrays;
public class FunctionUse {
public static void main(String []args) {
Arrays.stream("4, -9, 16".split(", "))
.map(Integer::parseInt)
.map(i -> (i < 0) ? -i : i)
.forEach(System.out::println);
}
}
Prints:
4
9
16
Function interface
Function interface
A Function<T, R> “operates” on something and
returns something: it takes one argument (of
generic type T) and returns an object (of generic
type R). You can call apply() method on a Function
object.
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
// other methods elided
}
Function interface: Example
Function<String, Integer> strLength = str -> str.length();
System.out.println(strLength.apply("supercalifragilisticexpialidocious"));
Prints:
34
Function interface: Example
import java.util.Arrays;
import java.util.function.Function;
public class CombineFunctions {
public static void main(String []args) {
Function<String, Integer> parseInt = Integer:: parseInt ;
Function<Integer, Integer> absInt = Math:: abs ;
Function<String, Integer> parseAndAbsInt = parseInt.andThen(absInt)
Arrays.stream("4, -9, 16".split(", "))
.map(parseAndAbsInt)
.forEach(System. out ::println);
}
}
Prints:
4
9
16
Supplier interface
import java.util.stream.Stream;
import java.util.Random;
class GenerateBooleans {
public static void main(String []args) {
Random random = new Random();
Stream.generate(random::nextBoolean)
.limit(2)
.forEach(System.out::println);
}
}
Prints two boolean
values “true” and “false”
in random order
Supplier interface
Supplier interface
A Supplier<T> “supplies” takes nothing but
returns something: it has no arguments and
returns an object (of generic type T). You can call
get() method on a Supplier object
@FunctionalInterface
public interface Supplier<T> {
T get();
// no other methods in this interface
}
Supplier interface: Example
Supplier<String> currentDateTime = () -> LocalDateTime.now().toString();
System.out.println(currentDateTime.get());
Prints current time:
2015-10-16T12:40:55.164
Summary of built-in interfaces in
java.util.function interface
❖ There are only four core functional interfaces in this
package: Predicate, Consumer, Function, and Supplier.
❖ The rest of the interfaces are primitive versions, binary
versions, and derived interfaces such as
UnaryOperator interface.
❖ These interfaces differ mainly on the signature of the
abstract methods they declare.
❖ You need to choose the suitable functional interface
based on the context and your need.
Agenda
• Introduction & Overview
• Lambdas
• Functional interfaces
• Streams
• Parallel streams
• Date & Time package
• Refactoring to Java 8
Java 8 streams (and parallel streams):
Excellent example of applying functional
programming in practice
But what are streams?
Arrays.stream(Object.class.getMethods())
.map(method -> method.getName())
.distinct()
.forEach(System.out::println);
wait
equals
toString
hashCode
getClass
notify
notifyAll
Method[] objectMethods = Object.class.getMethods();
Stream<Method> objectMethodStream = Arrays.stream(objectMethods);
Stream<String> objectMethodNames
= objectMethodStream.map(method -> method.getName());
Stream<String> uniqueObjectMethodNames = objectMethodNames.distinct();
uniqueObjectMethodNames.forEach(System.out::println);
Arrays.stream(Object.class.getMethods())
.map(method -> method.getName())
.distinct()
.forEach(System.out::println);
Breaking up into
separate (looong)
stream pipeline
Stream	
source	
Intermediate	
opera1ons	
Terminal	
opera1on	
stream	
stream	
Examples:	
IntStream.range(),		
Arrays.stream()	
Examples:	
map(),	filter(),		
dis1nct(),	sorted()	
Examples:	
sum(),	collect(),		
forEach(),	reduce()
DoubleStream.	
of(1.0,	4.0,	9.0)		
map(Math::sqrt)		
.peek(System.out::
println)		
Stream		
Source	(with	
elements	1.0,	
4.0,	and	9.0)	
Intermediate	
Opera=on	1	
(maps	to	
element	values	
1.0,	2.0,	and	3.0)	
Intermediate	
Opera=on	2	
(prints	1.0,	2.0,	
and	3.0)	
.sum();		
Terminal	
Opera=on	
(returns	the	
sum	6.0)	
DoubleStream.of(1.0, 4.0, 9.0)
.map(Math::sqrt)
.peek(System.out::println)
.sum();
IntStream.range(1, 6)
You can use range or iterate
factory methods in the
IntStream interface
IntStream.iterate(1, i -> i + 1).limit(5)
1	 	2 	3 	4 	5	
1	 	4 	9 	16 		25	
map(i	->	i	*	i)	
IntStream.range(1, 5).map(i -> i * i).forEach(System.out::println);
Using streams instead of imperative for i = 1 to 5, print i * i
Stream.of (1, 2, 3, 4, 5)
.map(i -> i * i)
.peek(i -> System.out.printf("%d ", i))
.count();
prints: 1 4 9 16 25
stream can be
infinite
IntStream.iterate(0, i -> i + 2).forEach(System.out::println);
This code creates infinite stream of even numbers!
IntStream
.iterate(0, i -> i + 2)
.limit(5)
.forEach(System.out::println);
Using the “limit” function to limit the stream to 5 integers
IntStream chars = "bookkeep".chars();
System.out.println(chars.count());
chars.distinct().sorted().forEach(ch -> System.out.printf("%c ", ch));
Cannot “reuse” a stream; this code
throws IllegalStateException
Streams are lazy!
Files.lines(Paths.get("FileRead.java")).forEach(System.out::println);
This code prints the contents of
the file “FileRead.java” in the
current directory
Pattern.compile(" ").splitAsStream("java 8 streams").forEach(System.out::println);
This code splits the input string “java 8
streams” based on whitespace and hence
prints the strings “java”, “8”, and
“streams” on the console
new Random().ints().limit(5).forEach(System.out::println);
Generates 5 random integers and prints
them on the console
"hello".chars().sorted().forEach(ch -> System.out.printf("%c ", ch));
Extracts characters in the string “hello”,
sorts the chars and prints the chars
Agenda
• Introduction & Overview
• Lambdas
• Functional interfaces
• Streams
• Parallel streams
• Date & Time package
• Refactoring to Java 8
Parallel Streams
race conditions
deadlocks
I really really hate
concurrency problems
Parallel code
Serial code
Sometimes, dreams do come
true even at 86 :-)
So, keep dreaming till you
become 86!
long numOfPrimes = LongStream.rangeClosed(2, 100_000)
.filter(PrimeNumbers::isPrime)
.count();
System.out.println(numOfPrimes);
Prints 9592
2.510 seconds
Parallel code
Serial code
Let’s flip the switch by
calling parallel() function
long numOfPrimes = LongStream.rangeClosed(2, 100_000)
.parallel()
.filter(PrimeNumbers::isPrime)
.count();
System.out.println(numOfPrimes);
Prints 9592
1.235 seconds
Wow! That’s an awesome flip
switch!
Internally, parallel streams make
use of fork-join framework
import java.util.Arrays;
class StringConcatenator {
public static String result = "";
public static void concatStr(String str) {
result = result + " " + str;
}
}
class StringSplitAndConcatenate {
public static void main(String []args) {
String words[] = "the quick brown fox jumps over the lazy dog".split(" ");
Arrays.stream(words).forEach(StringConcatenator::concatStr);
System.out.println(StringConcatenator.result);
}
}
Gives wrong results with
with parallel() call
Agenda
• Introduction & Overview
• Lambdas
• Functional interfaces
• Streams
• Parallel streams
• Date & Time package
• Refactoring to Java 8
–Craig Larman
"The critical design tool for software development
is a mind well educated in design principles"
Design Smells: Example
Discussion Example
// using java.util.Date
Date today = new Date();
System.out.println(today);
$ java DateUse
Wed Dec 02 17:17:08 IST 2015
Why should we get the
time and timezone details
if I only want a date? Can
I get rid of these parts?
No!
So What?!
Date today = new Date();
System.out.println(today);
Date todayAgain = new Date();
System.out.println(todayAgain);
System.out.println(today.compareTo(todayAgain) == 0);
Thu Mar 17 13:21:55 IST 2016
Thu Mar 17 13:21:55 IST 2016
false
What is going
on here?
Joda API
JSR 310: Java Date and Time API
Stephen Colebourne
Refactoring for Date
Replace inheritance
with delegation
java.time package!
Date, Calendar, and TimeZone
Java 8 replaces
these types
Refactored Solution
LocalDate today = LocalDate.now();
System.out.println(today);
LocalDate todayAgain = LocalDate.now();
System.out.println(todayAgain);
System.out.println(today.compareTo(todayAgain) == 0);
2016-03-17
2016-03-17
true
Works fine
now!
Refactored Example …
You can use only date,
time, or even timezone,
and combine them as
needed!
LocalDate today = LocalDate.now();
System.out.println(today);
LocalTime now = LocalTime.now();
System.out.println(now);
ZoneId id = ZoneId.of("Asia/Tokyo");
System.out.println(id);
LocalDateTime todayAndNow = LocalDateTime.now();
System.out.println(todayAndNow);
ZonedDateTime todayAndNowInTokyo = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
System.out.println(todayAndNowInTokyo);
2016-03-17
13:28:06.927
Asia/Tokyo
2016-03-17T13:28:06.928
2016-03-17T16:58:06.929+09:00[Asia/Tokyo]
“Fluent interfaces”
❖ Code is more readable and easier to use:
❖ Classes in this package have numerous static methods
(many of them factory methods)
❖ Methods in the classes follow a common naming
convention (for example, they use the prefixes plus
and minus to add or subtract date or time values)
java.time Sub-packages
❖ java.time.temporal —Accesses date/time fields and
units
❖ java.time.format —Formats the input and output of
date/time objects
❖ java.time.zone —Handles time zones
❖ java.time.chrono —Supports calendar systems such as
Japanese and Thai calendars
ISO-8601 Calendar System Format
❖ The Java 8 date and time API uses ISO 8601 as the
default calendar format.
❖ In this internationally accepted format, the date and
time values are sorted from the largest to the smallest
unit of time: year, month/week, day, hour, minute,
second, and millisecond/nanosecond.
❖ Example: LocalDate is represented in the in a year-
month-day format (YYYY-MM-DD), as in, 2015-10-26.
java.time.LocalDate
LocalDate newYear2016 = LocalDate.of(2016, 1, 1);
System.out.println("New year 2016: " + newYear2016);
New year 2016: 2016-01-01
java.time.LocalDate
LocalDate valentinesDay = LocalDate.of(2016, 14, 2);
System.out.println("Valentine's day is on: " + valentinesDay);
Exception in thread "main"
java.time.DateTimeException: Invalid value
for MonthOfYear(valid values 1 - 12): 14
java.time.LocalDate
long visaValidityDays = 180L;
LocalDate currDate = LocalDate.now();
System.out.println("My Visa expires on: " + currDate.plusDays(visaValidityDays));
My Visa expires on: 2016-04-23
Important Methods in LocalDate
java.time.LocalTime
LocalTime currTime = LocalTime.now();
System.out.println("Current time is: " + currTime);
Current time is: 12:23:05.072
java.time.LocalTime
System.out.println(LocalTime.of(18,30));
prints: 18:30
java.time.LocalTime
long hours = 6;
long minutes = 30;
LocalTime currTime = LocalTime.now();
System.out.println("Current time is: " + currTime);
System.out.println("My meeting is at: " +
currTime.plusHours(hours).plusMinutes(minutes));
Current time is: 12:29:13.624
My meeting is at: 18:59:13.624
Important Methods in LocalTime
java.time.LocalDateTime
LocalDateTime currDateTime = LocalDateTime.now();
System.out.println("Today's date and current time is: " + currDateTime);
Today's date and current time is:
2015-10-29T21:04:36.376
java.time.LocalDateTime
LocalDateTime christmas = LocalDateTime.of(2015, 12, 25, 0, 0);
LocalDateTime newYear = LocalDateTime.of(2016, 1, 1, 0, 0);
System.out.println("New Year 2016 comes after Christmas 2015”
+ newYear.isAfter(christmas));
New Year 2016 comes after
Christmas 2015? true
java.time.LocalDateTime
LocalDateTime dateTime = LocalDateTime.now();
System.out.println("Today's date and current time: " + dateTime);
System.out.println("The date component is: " + dateTime.toLocalDate());
System.out.println("The time component is: " + dateTime.toLocalTime());
Today's date and current time:
2015-11-04T13:19:10.497
The date component is: 2015-11-04
The time component is: 13:19:10.497
java.time.Instant
import java.time.Instant;
public class UsingInstant {
public static void main(String args[]){
// prints the current timestamp with UTC as time zone
Instant currTimeStamp = Instant.now();
System.out.println("Instant timestamp is: "+ currTimeStamp);
// prints the number of seconds as Unix timestamp from epoch time
System.out.println("Number of seconds elapsed: " + currTimeStamp.getEpochSecond());
// prints the Unix timestamp in milliseconds
System.out.println("Number of milliseconds elapsed: " + currTimeStamp.toEpochMilli());
}
}
Instant timestamp is: 2015-11-02T03:16:04.502Z
Number of seconds elapsed: 1446434164
Number of milliseconds elapsed: 1446434164502
java.time.Period
LocalDate manufacturingDate = LocalDate.of(2016, Month.JANUARY, 1);
LocalDate expiryDate = LocalDate.of(2018, Month.JULY, 18);
Period expiry = Period.between(manufacturingDate, expiryDate);
System.out.printf("Medicine will expire in: %d years, %d months, and %d days (%s)n",
expiry.getYears(), expiry.getMonths(), expiry.getDays(), expiry);
Medicine will expire in: 2 years, 6 months, and 17
days (P2Y6M17D)
Important Methods in Period
The Java 8 date and time API differentiates how humans
and computers use date- and time-related information.
For example, the Instant class represents a Unix
timestamp and internally uses long and int variables.
Instant values are not very readable or usable by
humans because the class does not support methods
related to day, month, hours, and so on (in contrast, the
Period class supports such methods).
java.time.Duration
LocalDateTime comingMidnight =
LocalDateTime.of(LocalDate.now().plusDays(1), LocalTime.MIDNIGHT);
LocalDateTime now = LocalDateTime.now();
Duration between = Duration.between(now, comingMidnight);
System.out.println(between);
PT7H13M42.003S
Important Methods in Duration
Summary of Instant, Period and Duration
TemporalUnit
import java.time.temporal.ChronoUnit;
public class ChronoUnitValues {
public static void main(String []args) {
System.out.println("ChronoUnit DateBased TimeBased Duration");
System.out.println("---------------------------------------");
for(ChronoUnit unit : ChronoUnit.values()) {
System.out.printf("%10s t %b tt %b tt %s %n”,
unit, unit.isDateBased(), unit.isTimeBased(), unit.getDuration());
}
}
}
ZoneId
System.out.println("My zone id is: " + ZoneId.systemDefault());
My zone id is: Asia/Kolkata
ZoneId AsiaKolkataZoneId = ZoneId.of("Asia/Kolkata");
ZonedDateTime
LocalDate currentDate = LocalDate.now();
LocalTime currentTime = LocalTime.now();
ZoneId myZone = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = ZonedDateTime.of(currentDate,
currentTime, myZone);
System.out.println(zonedDateTime);
2015-11-05T11:38:40.647+05:30[Asia/Kolkata]
ZonedDateTime
ZoneId myZone = ZoneId.of("Asia/Kolkata");
LocalDateTime dateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = dateTime.atZone(myZone);
ZoneOffset zoneOffset = zonedDateTime.getOffset();
System.out.println(zoneOffset);
+05:30
ZonedDateTime
ZoneId singaporeZone = ZoneId.of(“Asia/Singapore");
ZonedDateTime dateTimeInSingapore =
ZonedDateTime.of(LocalDateTime.of(2016, Month.JANUARY, 1, 6, 0), singaporeZone);
ZoneId aucklandZone = ZoneId.of("Pacific/Auckland");
ZonedDateTime sameDateTimeInAuckland =
dateTimeInSingapore.withZoneSameInstant(aucklandZone);
Duration timeDifference = Duration.between(
dateTimeInSingapore.toLocalTime(),
sameDateTimeInAuckland.toLocalTime());
System.out.printf("Time difference between %s and %s zones is %d hours”,
singaporeZone, aucklandZone, timeDifference.toHours());
Time difference between Asia/Singapore and
Pacific/Auckland zones is 5 hours
Daylight Savings
ZoneId kolkataZone = ZoneId.of("Asia/Kolkata");
Duration kolkataDST = kolkataZone.getRules().getDaylightSavings(Instant.now());
System.out.printf("Kolkata zone DST is: %d hours %n", kolkataDST.toHours());
ZoneId aucklandZone = ZoneId.of("Pacific/Auckland");
Duration aucklandDST = aucklandZone.getRules().getDaylightSavings(Instant.now());
System.out.printf("Auckland zone DST is: %d hours", aucklandDST.toHours());
Kolkata zone DST is: 0 hours
Auckland zone DST is: 1 hours
DateTimeFormatter
Predefined formatters:
• ISO_DATE (2015-11-05)
• ISO_TIME (11:25:47.624)
• RFC_1123_DATE_TIME (Thu, 5 Nov 2015 11:27:22 +0530)
• ISO_ZONED_DATE_TIME (2015-11-05T11:30:33.49+05:30[Asia/Kolkata])
DateTimeFormatter
Wake up time: 06:00:00
LocalTime wakeupTime = LocalTime.of(6, 0, 0);
System.out.println("Wake up time: " + DateTimeFormatter.ISO_TIME.format(wakeupTime));
01 Jan 2016
DateTimeFormatter customFormat = DateTimeFormatter.ofPattern("dd MMM yyyy");
System.out.println(customFormat.format(LocalDate.of(2016, Month.JANUARY, 01)));
Uppercase and lowercase letters can have similar or
different meanings when used in format strings for
dates and times. Read the Javadoc for these patterns
carefully before trying to use these letters. For example,
in dd-MM-yy, MM refers to month; however, in dd-mm-
yy, mm refers to minutes !
Formatting Dates
• G (era: BC, AD)
• y (year of era: 2015, 15)
• Y (week-based year: 2015, 15)
• M (month: 11, Nov, November)
• w (week in year: 13)
• W (week in month: 2)
• E (day name in week: Sun, Sunday)
• D (day of year: 256)
• d (day of month: 13)
Custom Date Patterns
public class CustomDatePatterns {
public static void main(String []args) {
// patterns from simple to complex ones
String [] dateTimeFormats = {
"dd-MM-yyyy", /* d is day (in month), M is month, y is year */
"d '('E')' MMM, YYYY", /*E is name of the day (in week), Y is year*/
"w'th week of' YYYY", /* w is the week of the year */
"EEEE, dd'th' MMMM, YYYY" /*E is day name in the week */
};
LocalDateTime now = LocalDateTime.now();
for(String dateTimeFormat : dateTimeFormats) {
System.out.printf("Pattern "%s" is %s %n", dateTimeFormat,
DateTimeFormatter.ofPattern(dateTimeFormat).format(now));
}
}
} Pattern "dd-MM-yyyy" is 05-11-2015
Pattern "d '('E')' MMM, YYYY" is 5 (Thu) Nov, 2015
Pattern "w'th week of' YYYY" is 45th week of 2015
Pattern "EEEE, dd'th' MMMM, YYYY" is Thursday, 05th November, 2015
Formatting Times
• a (marker for the text a.m./p.m. marker)
• H (hour: value range 0–23)
• k (hour: value range 1–24)
• K (hour in a.m./p.m.: value range 0–11)
• h (hour in a.m./p.m.: value range 1–12)
• m (minute)
• s (second)
• S (fraction of a second)
• z (time zone: general time-zone format)
Custom Time Patterns
class CustomTimePatterns {
public static void main(String []args) {
// patterns from simple to complex ones
String [] timeFormats = {
"h:mm", /* h is hour in am/pm (1-12), m is minute */
"hh 'o''clock'", /* '' is the escape sequence to print a single quote */
"H:mm a", /* H is hour in day (0-23), a is am/pm*/
"hh:mm:ss:SS", /* s is seconds, S is milliseconds */
"K:mm:ss a" /* K is hour in am/pm(0-11) */
};
LocalTime now = LocalTime.now();
for(String timeFormat : timeFormats) {
System.out.printf("Time in pattern "%s" is %s %n", timeFormat,
DateTimeFormatter.ofPattern(timeFormat).format(now));
}
}
}
Time in pattern "h:mm" is 12:27
Time in pattern "hh 'o''clock'" is 12 o'clock
Time in pattern "H:mm a" is 12:27 PM
Time in pattern "hh:mm:ss:SS" is 12:27:10:41
Time in pattern "K:mm:ss a" is 0:27:10 PM
Flight Travel - Time Calculation - Example
DateTimeFormatter dateTimeFormatter =
DateTimeFormatter.ofPattern("dd MMM yyyy hh.mm a");
// Leaving on 1st Jan 2016, 6:00am from "Singapore"
ZonedDateTime departure = ZonedDateTime.of(
LocalDateTime.of(2016, Month.JANUARY, 1, 6, 0),
ZoneId.of("Asia/Singapore"));
System.out.println("Departure: " + dateTimeFormatter.format(departure));
// Arrival on the same day in 10 hours in "Auckland"
ZonedDateTime arrival =
departure.withZoneSameInstant(ZoneId.of("Pacific/Auckland")).plusHours(10);
System.out.println("Arrival: " + dateTimeFormatter.format(arrival));
Departure: 01 Jan 2016 06.00 AM
Arrival: 01 Jan 2016 09.00 PM
Agenda
• Introduction & Overview
• Lambdas
• Functional interfaces
• Streams
• Parallel streams
• Date & Time package
• Refactoring to Java 8
Examples of refactorings (to Java 8)
❖ Convert anonymous inner
classes to lambda expressions
(when they are functional
interfaces)
❖ Convert for/foreach loops to
streams (i.e., external iteration
to internal iteration)
Refactoring loops to streams
❖ Replace if conditions with ‘filter’ and calls to methods
that return a boolean value (Predicate)
❖ Replace accumulation operations with reduce (or its
special forms like sum, count, etc).
Source: LAMBDAFICATOR: From Imperative to Functional Programming through Automated Refactoring. Lyle Franklin; Alex
Gyori; Jan Lahoda; Danny Dig. 35th International Conference on Software Engineering (ICSE), 2013.
Tool support for refactoring
❖ Most Java IDEs provide
suggestions to automatically
refactor to lambdas and
streams
❖ IDEs that support Java 8
refactoring include: Eclipse,
IntelliJ Idea and NetBeans
Refactoring suggestions in Netbeans
Image source: http://refactoring.info/tools/LambdaFicator/
Java 8 Migration Aids in IntelliJ IDEA
Image source: https://www.jetbrains.com/help/img/idea/ij_java_8_inspection_results_migration_runnable.png
Java 8 Refactorings in IntelliJ IDEA
Image source: https://www.jetbrains.com/help/img/idea/ij_java_8_replace_method_reference_with_lambda.png
https://www.jetbrains.com/help/img/idea/ij_java_8_can_be_replaced_with_method_ref.png
Refactoring suggestions in Netbeans
Image source: http://refactoring.info/tools/LambdaFicator/
Refactoring suggestions in Netbeans
Image source: http://refactoring.info/tools/LambdaFicator/
Suggested Reading
❖ Refactoring with Loops and Collection Pipelines
(Martin Fowler, 2015)
❖ Pragmatic Functional Refactoring with Java 8 (Raoul-
Gabriel Urma & Richard Warburton, 2015)
❖ Migrating to Java 8 (IntelliJ IDEA, 2016)
Meetups
hYp://www.meetup.com/JavaScript-Meetup-Bangalore/	
hYp://www.meetup.com/Container-Developers-Meetup-Bangalore/		
hYp://www.meetup.com/So^ware-Cra^smanship-Bangalore-Meetup/	
hYp://www.meetup.com/Core-Java-Meetup-Bangalore/	
hYp://www.meetup.com/Technical-Writers-Meetup-Bangalore/	
hYp://www.meetup.com/CloudOps-Meetup-Bangalore/	
hYp://www.meetup.com/Bangalore-SDN-IoT-NetworkVirtualiza7on-Enthusiasts/	
hYp://www.meetup.com/So^wareArchitectsBangalore/
Image credits
❖ http://mayhemandmuse.com/wp-content/uploads/2013/04/This-optical-illusion-drawing-by-WE-
Hill-shows-both-his-wife-and-his-mother-in-law.jpg
❖ http://www.webtrafficroi.com/wp-content/uploads/2012/10/mahatma-gandhi-apple-think-
different.jpg
❖ http://rexx-language-association-forum.44760.x6.nabble.com/file/n2236/Ruby-lambda-function.jpg
❖ http://www.ibm.com/developerworks/library/j-jn16/figure1.png
❖ http://www.ibm.com/developerworks/library/j-jn16/figure2.png
❖ http://img.viralpatel.net/2014/01/java-lambda-expression.png
❖ http://www.codercaste.com/wp-content/uploads/2011/01/animals.png
❖ http://blog.takipi.com/wp-content/uploads/2014/03/blog_lambada_2.png
❖ http://quotespictures.com/wp-content/uploads/2014/01/it-is-not-the-strongest-of-the-species-that-
survive-nor-the-most-intelligent-but-the-one-most-responsive-to-change-charles-darwin.jpg
❖ http://7-themes.com/data_images/out/27/6859733-surfing-wallpaper.jpg
ganesh@codeops.tech @GSamarthyam
www.codeops.tech slideshare.net/sgganesh
+91 98801 64463 bit.ly/sgganesh

More Related Content

What's hot

Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Edureka!
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8Knoldus Inc.
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features OverviewSergii Stets
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsGuy Nir
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockitoshaunthomas999
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesGanesh Samarthyam
 
Java 10 New Features
Java 10 New FeaturesJava 10 New Features
Java 10 New FeaturesAli BAKAN
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in JavaErhan Bagdemir
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
java 8 new features
java 8 new features java 8 new features
java 8 new features Rohit Verma
 

What's hot (20)

Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Lazy java
Lazy javaLazy java
Lazy java
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Spring ioc
Spring iocSpring ioc
Spring ioc
 
Java 10 New Features
Java 10 New FeaturesJava 10 New Features
Java 10 New Features
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
Log4 J
Log4 JLog4 J
Log4 J
 
Hibernate
Hibernate Hibernate
Hibernate
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 

Viewers also liked

Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
 
Choosing Between Cross Platform of Native Development
Choosing	Between Cross Platform of Native DevelopmentChoosing	Between Cross Platform of Native Development
Choosing Between Cross Platform of Native DevelopmentCodeOps Technologies LLP
 
DevOps Fundamentals: A perspective on DevOps Culture
DevOps Fundamentals: A perspective on DevOps Culture DevOps Fundamentals: A perspective on DevOps Culture
DevOps Fundamentals: A perspective on DevOps Culture CodeOps Technologies LLP
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesGanesh Samarthyam
 
Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkRefactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkCodeOps Technologies LLP
 
Solid Principles Of Design (Design Series 01)
Solid Principles Of Design (Design Series 01)Solid Principles Of Design (Design Series 01)
Solid Principles Of Design (Design Series 01)Heartin Jacob
 
Zero downtime release through DevOps Continuous Delivery
Zero downtime release through DevOps Continuous DeliveryZero downtime release through DevOps Continuous Delivery
Zero downtime release through DevOps Continuous DeliveryMurughan Palaniachari
 
Software Architecture - Principles Patterns and Practices - OSI Days Workshop...
Software Architecture - Principles Patterns and Practices - OSI Days Workshop...Software Architecture - Principles Patterns and Practices - OSI Days Workshop...
Software Architecture - Principles Patterns and Practices - OSI Days Workshop...CodeOps Technologies LLP
 

Viewers also liked (20)

Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
 
7 best quotes on dev ops
7 best quotes on dev ops7 best quotes on dev ops
7 best quotes on dev ops
 
Choosing Between Cross Platform of Native Development
Choosing	Between Cross Platform of Native DevelopmentChoosing	Between Cross Platform of Native Development
Choosing Between Cross Platform of Native Development
 
DevOps Fundamentals: A perspective on DevOps Culture
DevOps Fundamentals: A perspective on DevOps Culture DevOps Fundamentals: A perspective on DevOps Culture
DevOps Fundamentals: A perspective on DevOps Culture
 
Better java with design
Better java with designBetter java with design
Better java with design
 
Introduction to chef
Introduction to chefIntroduction to chef
Introduction to chef
 
DevOps - A Gentle Introduction
DevOps - A Gentle IntroductionDevOps - A Gentle Introduction
DevOps - A Gentle Introduction
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkRefactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech Talk
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Solid Principles Of Design (Design Series 01)
Solid Principles Of Design (Design Series 01)Solid Principles Of Design (Design Series 01)
Solid Principles Of Design (Design Series 01)
 
Zero downtime release through DevOps Continuous Delivery
Zero downtime release through DevOps Continuous DeliveryZero downtime release through DevOps Continuous Delivery
Zero downtime release through DevOps Continuous Delivery
 
DevOps Toolchain v1.0
DevOps Toolchain v1.0DevOps Toolchain v1.0
DevOps Toolchain v1.0
 
DevOps game marshmallow challenge
DevOps game marshmallow challengeDevOps game marshmallow challenge
DevOps game marshmallow challenge
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java 8 concurrency abstractions
Java 8 concurrency abstractionsJava 8 concurrency abstractions
Java 8 concurrency abstractions
 
Software Architecture - Principles Patterns and Practices - OSI Days Workshop...
Software Architecture - Principles Patterns and Practices - OSI Days Workshop...Software Architecture - Principles Patterns and Practices - OSI Days Workshop...
Software Architecture - Principles Patterns and Practices - OSI Days Workshop...
 

Similar to Modern Programming in Java 8 - Lambdas, Streams and Date Time API

Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsCodeOps Technologies LLP
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasGanesh Samarthyam
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New featuresSon Nguyen
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data ManagementAlbert Bifet
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdasshinolajla
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about LambdasRyan Knight
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Ganesh Samarthyam
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8 Dori Waldman
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingHenri Tremblay
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern JavaSina Madani
 
Jug Marche: Meeting June 2014. Java 8 hands on
Jug Marche: Meeting June 2014. Java 8 hands onJug Marche: Meeting June 2014. Java 8 hands on
Jug Marche: Meeting June 2014. Java 8 hands onOnofrio Panzarino
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 

Similar to Modern Programming in Java 8 - Lambdas, Streams and Date Time API (20)

Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and Streams
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New features
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about Lambdas
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern Java
 
Quick introduction to scala
Quick introduction to scalaQuick introduction to scala
Quick introduction to scala
 
Jug Marche: Meeting June 2014. Java 8 hands on
Jug Marche: Meeting June 2014. Java 8 hands onJug Marche: Meeting June 2014. Java 8 hands on
Jug Marche: Meeting June 2014. Java 8 hands on
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 

More from Ganesh Samarthyam

Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeGanesh Samarthyam
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”Ganesh Samarthyam
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGanesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationGanesh Samarthyam
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterGanesh Samarthyam
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Ganesh Samarthyam
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckGanesh Samarthyam
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageGanesh Samarthyam
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Ganesh Samarthyam
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz QuestionsGanesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz QuestionsGanesh Samarthyam
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizGanesh Samarthyam
 

More from Ganesh Samarthyam (20)

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quiz
 

Recently uploaded

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 

Recently uploaded (20)

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 

Modern Programming in Java 8 - Lambdas, Streams and Date Time API

  • 1. Modern Programming in Java 8 Lambdas, Streams and Date/Time API GANESH & HARI CODEOPS TECHNOLOGIES ganesh@codeops.tech hari@codeops.tech
  • 2.
  • 4. Agenda • Introduction & Overview • Lambdas • Functional interfaces • Streams • Parallel Streams • Date & Time package • Refactoring to Java 8
  • 6. Java is not your grandma’s language anymore!
  • 8. He he, but lambdas are fun, not scary
  • 9. List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); Consumer<String> printString = string -> System.out.println(string); strings.forEach(printString); Lambda functions!
  • 11. Lambdas is just a fancy name for functions without a name!
  • 12. What are lambda functions? ❖ (Java 8) One way to think about lambdas is “anonymous function” or “unnamed function” - they are functions without a name and are not associated with any class ❖ They don’t change external state
  • 13. What is functional programming? ❖ Functional languages view programs as an entity— called a function—that accepts inputs and produces output ❖ Functions are connected together by their outputs to other functions’ inputs ❖ Underlying approach: “Evaluate an expression. Then use the results for something else.”
  • 14. Perspective - for loops! List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); for(String string : strings) { System.out.println(string); } External Iteration
  • 15. Perspective - for loops! List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); strings.forEach(string -> System.out.println(string)); Internal Iteration
  • 16. Perspective - for loops! List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); strings.forEach(string -> System.out.println(string)); Internal Iteration List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); for(String string : strings) { System.out.println(string); } External Iteration
  • 17. Perspective - for loops! List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); strings.forEach(string -> System.out.println(string)); Internal Iteration List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); for(String string : strings) { System.out.println(string); } External Iteration Procedural thinking Functional thinking
  • 18. You can use lambdas for some amazing stuff
  • 19. sedime nt pre- carbon ultra- filter post- carbon Filtered water E.g., you can compose lambda functions as in pipes-and-filters
  • 20. $ cat limerick.txt There was a young lady of Niger Who smiled as she rode on a tiger. They returned from the ride With the lady inside And a smile on the face of the tiger.
  • 21. $ cat limerick.txt | tr -cs "[:alpha:]" "n" | awk '{print length(), $0}' | sort | uniq 1 a 2 as 2 of 2 on 3 And 3 Who 3 she 3 the 3 was 4 They 4 With 4 face 4 from 4 lady 4 ride 4 rode 5 Niger 5 There 5 smile 5 tiger 5 young 6 inside 6 smiled 8 returned
  • 22. List<String> lines = Files.readAllLines(Paths.get("./limerick.txt"), Charset.defaultCharset()); Map<Integer, List<String>> wordGroups = lines.stream() .map(line -> line.replaceAll("W", "n").split("n")) .flatMap(Arrays::stream) .sorted() .distinct() .collect(Collectors.groupingBy(String::length)); wordGroups.forEach( (count, words) -> { words.forEach(word -> System.out.printf("%d %s %n", count, word)); }); 1 a 2 as 2 of 2 on 3 And 3 Who 3 she 3 the 3 was 4 They 4 With 4 face 4 from 4 lady 4 ride 4 rode 5 Niger 5 There 5 smile 5 tiger 5 young 6 inside 6 smiled 8 returned
  • 23. Lambdas & streams help in productive programming!
  • 24. public static void main(String []file) throws Exception { // process each file passed as argument // try opening the file with FileReader try (FileReader inputFile = new FileReader(file[0])) { int ch = 0; while( (ch = inputFile.read()) != -1) { // ch is of type int - convert it back to char System.out.print( (char)ch ); } } // try-with-resources will automatically release FileReader object } public static void main(String []file) throws Exception { Files.lines(Paths.get(file[0])).forEach(System.out::println); } Existing APIs are enriched with lambdas and streams support
  • 25. Java 8 is the new Groovy ;-) import java.io.*; class Type { public sta7c void main(String []files) { // process each file passed as argument for(String file : files) { // try opening the file with FileReader try (FileReader inputFile = new FileReader(file)) { int ch = 0; while( (ch = inputFile.read()) != -1) { // ch is of type int - convert it back to char System.out.print( (char)ch ); } } catch (FileNotFoundExcep7on fnfe) { System.err.prinR("Cannot open the given file %s ", file); } catch(IOExcep7on ioe) { System.err.prinR("Error when processing file %s; skipping it", file); } // try-with-resources will automa7cally release FileReader object } } } args.each { println new File(it).getText() }
  • 26. Agenda • Introduction & Overview • Lambdas • Functional interfaces • Streams • Parallel streams • Date & Time package • Refactoring to Java 8
  • 27. Java 8 lambdas - “Hello world!” interface LambdaFunction { void call(); } class FirstLambda { public static void main(String []args) { LambdaFunction lambdaFunction = () -> System.out.println("Hello world"); lambdaFunction.call(); } }
  • 28. Java 8 lambdas - “Hello world!” interface LambdaFunction { void call(); } class FirstLambda { public static void main(String []args) { LambdaFunction lambdaFunction = () -> System.out.println("Hello world"); lambdaFunction.call(); } } Functional interface - provides signature for lambda functions Lambda function/expression Call to the lambda Prints “Hello world” on the console when executed
  • 29. Parts of a lambda expression () -> System.out.println("Hello world"); No parameters, i.e., () Arrow operator that separates parameters and the body The lambda body Return type “void” inferred from the body
  • 30. Method references Method references - “syntactic sugar” for lambda functions They “route” function parameters arg -> System.out.println(arg) System.out::println
  • 31. Method references List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); Consumer<String> printString = System.out::println; strings.forEach(printString); Method reference List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); Consumer<String> printString = string -> System.out.println(string); strings.forEach(printString);
  • 32. Method references Cannot use method references when lambda functions do more than“routing” function parameters strings.forEach(string -> System.out.println(string.toUpperCase())); More processing here than just “routing” parameters
  • 33. Method references List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); Consumer<String> printString = System.out::println; strings.forEach(printString); public static void printUpperCaseString(String string) { System.out.println(string.toUpperCase()); } strings.forEach(MethodReference::printUpperCaseString);
  • 34. “Effectively final” variables import java.util.Arrays; import java.util.List; class PigLatin { public static void main(String []args) { String suffix = "ay"; List<String> strings = Arrays.asList("one", "two", "three", "four"); strings.forEach(string -> System.out.println(string + suffix)); } } Accessing “local variable” suffix here; hence it is considered “effectively final”
  • 35. “Effectively final” variables import java.util.Arrays; import java.util.List; class PigLatin { public static void main(String []args) { String suffix = "ay"; List<String> strings = Arrays.asList("one", "two", "three", “four"); suffix = "e"; // assign to suffix variable strings.forEach(string -> System.out.println(string + suffix)); } } PigLatinAssign.java:9: error: local variables referenced from a lambda expression must be final or effectively final strings.forEach(string -> System.out.println(string + suffix)); ^ 1 error
  • 36. Agenda • Introduction & Overview • Lambdas • Functional interfaces • Streams • Parallel streams • Date & Time package • Refactoring to Java 8
  • 37. Functional interfaces @FunctionalInterface interface LambdaFunction { void call(); } Functional interface Abstract method providing the signature of the lambda function Annotation to explicitly state that it is a functional interface
  • 38. Java 8 lambdas - “Hello world!” @FunctionalInterface interface LambdaFunction { void call(); } class FirstLambda { public static void main(String []args) { LambdaFunction lambdaFunction = () -> System.out.println("Hello world"); lambdaFunction.call(); } } Functional interface - provides signature for lambda functions Lambda function/expression Call to the lambda Prints “Hello world” on the console when executed
  • 39. Older Single Abstract Methods (SAMs) // in java.lang package interface Runnable { void run(); } // in java.util package interface Comparator<T> { boolean compare(T x, T y); } // java.awt.event package: interface ActionListener { void actionPerformed(ActionEvent e) } // java.io package interface FileFilter { boolean accept(File pathName); }
  • 40. Functional interfaces: Single abstract methods @FunctionalInterface interface LambdaFunction { void call(); // Single Abstract Method (SAM) }
  • 41. Using built-in functional interfaces // within Iterable interface default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } } // in java.util.function package @FunctionalInterface public interface Consumer<T> { void accept(T t); // the default andThen method elided }
  • 42. Using built-in functional interfaces List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); Consumer<String> printString = string -> System.out.println(string); strings.forEach(printString); List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); strings.forEach(string -> System.out.println(string));
  • 43. Default methods in interfaces public interface Iterator<E> { boolean hasNext(); E next(); default void remove() { throw new UnsupportedOperationException("remove"); } default void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); while (hasNext()) action.accept(next()); } }
  • 45. “Diamond” inheritance problem? interface Interface1 { default public void foo() { System.out.println("Interface1’s foo"); } } interface Interface2 { default public void foo() { System.out.println("Interface2’s foo"); } } public class Diamond implements Interface1, Interface2 { public static void main(String []args) { new Diamond().foo(); } } Error:(9, 8) java: class Diamond inherits unrelated defaults for foo() from types Interface1 and Interface2
  • 46. “Diamond” inheritance problem? interface Interface1 { default public void foo() { System.out.println("Interface1’s foo"); } } interface Interface2 { default public void foo() { System.out.println("Interface2’s foo"); } } public class Diamond implements Interface1, Interface2 { public void foo() { Interface1.super.foo(); } public static void main(String []args) { new Diamond().foo(); } } Add this definition to resolve the ambiguity
  • 47. “Diamond” inheritance problem? class BaseClass { public void foo() { System.out.println("BaseClass’s foo"); } } interface BaseInterface { default public void foo() { System.out.println("BaseInterface’s foo”); } } public class Diamond extends BaseClass implements BaseInterface { public static void main(String []args) { new Diamond().foo(); } } Compiles cleanly; Java 8 rules help deal with the diamond problem
  • 49. Built-in functional interfaces are a part of the java.util.function package (in Java 8)
  • 50. Built-in interfaces Predicate<T> Checks a condition and returns a boolean value as result In filter() method in java.util.stream.Stream which is used to remove elements in the stream that don’t match the given condition (i.e., predicate) asConsumer<T> Operation that takes an argument but returns nothing In forEach() method in collections and in java.util.stream.Stream; this method is used for traversing all the elements in the collection orFunction<T, R> Functions that take an argument and return a result In map() method in java.util.stream.Stream to transform or operate on the passed value and return a result. Supplier<T> Operation that returns a value to the caller (the returned value could be same or different values) In generate() method in java.util.stream.Stream to create a infinite stream of elements.
  • 51. Predicate interface Stream.of("hello", "world") .filter(str -> str.startsWith("h")) .forEach(System.out::println); The filter() method takes a Predicate as an argument (predicates are functions that check a condition and return a boolean value)
  • 53. Predicate interface A Predicate<T> “affirms” something as true or false: it takes an argument of type T, and returns a boolean value. You can call test() method on a Predicate object. @FunctionalInterface public interface Predicate<T> { boolean test(T t); // other methods elided }
  • 54. Predicate interface: Example import java.util.function.Predicate; public class PredicateTest { public static void main(String []args) { Predicate<String> nullCheck = arg -> arg != null; Predicate<String> emptyCheck = arg -> arg.length() > 0; Predicate<String> nullAndEmptyCheck = nullCheck.and(emptyCheck); String helloStr = "hello"; System.out.println(nullAndEmptyCheck.test(helloStr)); String nullStr = null; System.out.println(nullAndEmptyCheck.test(nullStr)); } } Prints: true false
  • 55. Predicate interface: Example import java.util.List; import java.util.ArrayList; public class RemoveIfMethod { public static void main(String []args) { List<String> greeting = new ArrayList<>(); greeting.add("hello"); greeting.add("world"); greeting.removeIf(str -> !str.startsWith("h")); greeting.forEach(System.out::println); } } Prints: hello
  • 56. Consumer interface Stream.of("hello", "world") .forEach(System.out::println); // void forEach(Consumer<? super T> action); Prints: hello world
  • 58. Consumer interface A Consumer<T> “consumes” something: it takes an argument (of generic type T) and returns nothing (void). You can call accept() method on a Consumer object. @FunctionalInterface public interface Consumer<T> { void accept(T t); // the default andThen method elided }
  • 59. Consumer interface: Example Consumer<String> printUpperCase = str -> System.out.println(str.toUpperCase()); printUpperCase.accept("hello"); Prints: HELLO
  • 60. Consumer interface: Example import java.util.stream.Stream; import java.util.function.Consumer; class ConsumerUse { public static void main(String []args) { Stream<String> strings = Stream.of("hello", "world"); Consumer<String> printString = System.out::println; strings.forEach(printString); } } Prints: hello world
  • 61. Function interface import java.util.Arrays; public class FunctionUse { public static void main(String []args) { Arrays.stream("4, -9, 16".split(", ")) .map(Integer::parseInt) .map(i -> (i < 0) ? -i : i) .forEach(System.out::println); } } Prints: 4 9 16
  • 63. Function interface A Function<T, R> “operates” on something and returns something: it takes one argument (of generic type T) and returns an object (of generic type R). You can call apply() method on a Function object. @FunctionalInterface public interface Function<T, R> { R apply(T t); // other methods elided }
  • 64. Function interface: Example Function<String, Integer> strLength = str -> str.length(); System.out.println(strLength.apply("supercalifragilisticexpialidocious")); Prints: 34
  • 65. Function interface: Example import java.util.Arrays; import java.util.function.Function; public class CombineFunctions { public static void main(String []args) { Function<String, Integer> parseInt = Integer:: parseInt ; Function<Integer, Integer> absInt = Math:: abs ; Function<String, Integer> parseAndAbsInt = parseInt.andThen(absInt) Arrays.stream("4, -9, 16".split(", ")) .map(parseAndAbsInt) .forEach(System. out ::println); } } Prints: 4 9 16
  • 66. Supplier interface import java.util.stream.Stream; import java.util.Random; class GenerateBooleans { public static void main(String []args) { Random random = new Random(); Stream.generate(random::nextBoolean) .limit(2) .forEach(System.out::println); } } Prints two boolean values “true” and “false” in random order
  • 68. Supplier interface A Supplier<T> “supplies” takes nothing but returns something: it has no arguments and returns an object (of generic type T). You can call get() method on a Supplier object @FunctionalInterface public interface Supplier<T> { T get(); // no other methods in this interface }
  • 69. Supplier interface: Example Supplier<String> currentDateTime = () -> LocalDateTime.now().toString(); System.out.println(currentDateTime.get()); Prints current time: 2015-10-16T12:40:55.164
  • 70. Summary of built-in interfaces in java.util.function interface ❖ There are only four core functional interfaces in this package: Predicate, Consumer, Function, and Supplier. ❖ The rest of the interfaces are primitive versions, binary versions, and derived interfaces such as UnaryOperator interface. ❖ These interfaces differ mainly on the signature of the abstract methods they declare. ❖ You need to choose the suitable functional interface based on the context and your need.
  • 71. Agenda • Introduction & Overview • Lambdas • Functional interfaces • Streams • Parallel streams • Date & Time package • Refactoring to Java 8
  • 72. Java 8 streams (and parallel streams): Excellent example of applying functional programming in practice
  • 73. But what are streams?
  • 75. Method[] objectMethods = Object.class.getMethods(); Stream<Method> objectMethodStream = Arrays.stream(objectMethods); Stream<String> objectMethodNames = objectMethodStream.map(method -> method.getName()); Stream<String> uniqueObjectMethodNames = objectMethodNames.distinct(); uniqueObjectMethodNames.forEach(System.out::println); Arrays.stream(Object.class.getMethods()) .map(method -> method.getName()) .distinct() .forEach(System.out::println); Breaking up into separate (looong)
  • 78. IntStream.range(1, 6) You can use range or iterate factory methods in the IntStream interface IntStream.iterate(1, i -> i + 1).limit(5)
  • 79. 1 2 3 4 5 1 4 9 16 25 map(i -> i * i) IntStream.range(1, 5).map(i -> i * i).forEach(System.out::println); Using streams instead of imperative for i = 1 to 5, print i * i
  • 80. Stream.of (1, 2, 3, 4, 5) .map(i -> i * i) .peek(i -> System.out.printf("%d ", i)) .count(); prints: 1 4 9 16 25
  • 81. stream can be infinite IntStream.iterate(0, i -> i + 2).forEach(System.out::println); This code creates infinite stream of even numbers!
  • 82. IntStream .iterate(0, i -> i + 2) .limit(5) .forEach(System.out::println); Using the “limit” function to limit the stream to 5 integers
  • 83. IntStream chars = "bookkeep".chars(); System.out.println(chars.count()); chars.distinct().sorted().forEach(ch -> System.out.printf("%c ", ch)); Cannot “reuse” a stream; this code throws IllegalStateException
  • 85. Files.lines(Paths.get("FileRead.java")).forEach(System.out::println); This code prints the contents of the file “FileRead.java” in the current directory
  • 86. Pattern.compile(" ").splitAsStream("java 8 streams").forEach(System.out::println); This code splits the input string “java 8 streams” based on whitespace and hence prints the strings “java”, “8”, and “streams” on the console
  • 87. new Random().ints().limit(5).forEach(System.out::println); Generates 5 random integers and prints them on the console
  • 88. "hello".chars().sorted().forEach(ch -> System.out.printf("%c ", ch)); Extracts characters in the string “hello”, sorts the chars and prints the chars
  • 89. Agenda • Introduction & Overview • Lambdas • Functional interfaces • Streams • Parallel streams • Date & Time package • Refactoring to Java 8
  • 92.
  • 94.
  • 95. I really really hate concurrency problems
  • 97. Sometimes, dreams do come true even at 86 :-)
  • 98. So, keep dreaming till you become 86!
  • 99. long numOfPrimes = LongStream.rangeClosed(2, 100_000) .filter(PrimeNumbers::isPrime) .count(); System.out.println(numOfPrimes); Prints 9592 2.510 seconds
  • 100. Parallel code Serial code Let’s flip the switch by calling parallel() function
  • 101. long numOfPrimes = LongStream.rangeClosed(2, 100_000) .parallel() .filter(PrimeNumbers::isPrime) .count(); System.out.println(numOfPrimes); Prints 9592 1.235 seconds
  • 102. Wow! That’s an awesome flip switch!
  • 103. Internally, parallel streams make use of fork-join framework
  • 104.
  • 105. import java.util.Arrays; class StringConcatenator { public static String result = ""; public static void concatStr(String str) { result = result + " " + str; } } class StringSplitAndConcatenate { public static void main(String []args) { String words[] = "the quick brown fox jumps over the lazy dog".split(" "); Arrays.stream(words).forEach(StringConcatenator::concatStr); System.out.println(StringConcatenator.result); } } Gives wrong results with with parallel() call
  • 106. Agenda • Introduction & Overview • Lambdas • Functional interfaces • Streams • Parallel streams • Date & Time package • Refactoring to Java 8
  • 107. –Craig Larman "The critical design tool for software development is a mind well educated in design principles"
  • 109. Discussion Example // using java.util.Date Date today = new Date(); System.out.println(today); $ java DateUse Wed Dec 02 17:17:08 IST 2015 Why should we get the time and timezone details if I only want a date? Can I get rid of these parts? No!
  • 110. So What?! Date today = new Date(); System.out.println(today); Date todayAgain = new Date(); System.out.println(todayAgain); System.out.println(today.compareTo(todayAgain) == 0); Thu Mar 17 13:21:55 IST 2016 Thu Mar 17 13:21:55 IST 2016 false What is going on here?
  • 111. Joda API JSR 310: Java Date and Time API Stephen Colebourne
  • 112. Refactoring for Date Replace inheritance with delegation
  • 113. java.time package! Date, Calendar, and TimeZone Java 8 replaces these types
  • 114. Refactored Solution LocalDate today = LocalDate.now(); System.out.println(today); LocalDate todayAgain = LocalDate.now(); System.out.println(todayAgain); System.out.println(today.compareTo(todayAgain) == 0); 2016-03-17 2016-03-17 true Works fine now!
  • 115. Refactored Example … You can use only date, time, or even timezone, and combine them as needed! LocalDate today = LocalDate.now(); System.out.println(today); LocalTime now = LocalTime.now(); System.out.println(now); ZoneId id = ZoneId.of("Asia/Tokyo"); System.out.println(id); LocalDateTime todayAndNow = LocalDateTime.now(); System.out.println(todayAndNow); ZonedDateTime todayAndNowInTokyo = ZonedDateTime.now(ZoneId.of("Asia/Tokyo")); System.out.println(todayAndNowInTokyo); 2016-03-17 13:28:06.927 Asia/Tokyo 2016-03-17T13:28:06.928 2016-03-17T16:58:06.929+09:00[Asia/Tokyo]
  • 116. “Fluent interfaces” ❖ Code is more readable and easier to use: ❖ Classes in this package have numerous static methods (many of them factory methods) ❖ Methods in the classes follow a common naming convention (for example, they use the prefixes plus and minus to add or subtract date or time values)
  • 117. java.time Sub-packages ❖ java.time.temporal —Accesses date/time fields and units ❖ java.time.format —Formats the input and output of date/time objects ❖ java.time.zone —Handles time zones ❖ java.time.chrono —Supports calendar systems such as Japanese and Thai calendars
  • 118. ISO-8601 Calendar System Format ❖ The Java 8 date and time API uses ISO 8601 as the default calendar format. ❖ In this internationally accepted format, the date and time values are sorted from the largest to the smallest unit of time: year, month/week, day, hour, minute, second, and millisecond/nanosecond. ❖ Example: LocalDate is represented in the in a year- month-day format (YYYY-MM-DD), as in, 2015-10-26.
  • 119. java.time.LocalDate LocalDate newYear2016 = LocalDate.of(2016, 1, 1); System.out.println("New year 2016: " + newYear2016); New year 2016: 2016-01-01
  • 120. java.time.LocalDate LocalDate valentinesDay = LocalDate.of(2016, 14, 2); System.out.println("Valentine's day is on: " + valentinesDay); Exception in thread "main" java.time.DateTimeException: Invalid value for MonthOfYear(valid values 1 - 12): 14
  • 121. java.time.LocalDate long visaValidityDays = 180L; LocalDate currDate = LocalDate.now(); System.out.println("My Visa expires on: " + currDate.plusDays(visaValidityDays)); My Visa expires on: 2016-04-23
  • 122. Important Methods in LocalDate
  • 123. java.time.LocalTime LocalTime currTime = LocalTime.now(); System.out.println("Current time is: " + currTime); Current time is: 12:23:05.072
  • 125. java.time.LocalTime long hours = 6; long minutes = 30; LocalTime currTime = LocalTime.now(); System.out.println("Current time is: " + currTime); System.out.println("My meeting is at: " + currTime.plusHours(hours).plusMinutes(minutes)); Current time is: 12:29:13.624 My meeting is at: 18:59:13.624
  • 126. Important Methods in LocalTime
  • 127. java.time.LocalDateTime LocalDateTime currDateTime = LocalDateTime.now(); System.out.println("Today's date and current time is: " + currDateTime); Today's date and current time is: 2015-10-29T21:04:36.376
  • 128. java.time.LocalDateTime LocalDateTime christmas = LocalDateTime.of(2015, 12, 25, 0, 0); LocalDateTime newYear = LocalDateTime.of(2016, 1, 1, 0, 0); System.out.println("New Year 2016 comes after Christmas 2015” + newYear.isAfter(christmas)); New Year 2016 comes after Christmas 2015? true
  • 129. java.time.LocalDateTime LocalDateTime dateTime = LocalDateTime.now(); System.out.println("Today's date and current time: " + dateTime); System.out.println("The date component is: " + dateTime.toLocalDate()); System.out.println("The time component is: " + dateTime.toLocalTime()); Today's date and current time: 2015-11-04T13:19:10.497 The date component is: 2015-11-04 The time component is: 13:19:10.497
  • 130. java.time.Instant import java.time.Instant; public class UsingInstant { public static void main(String args[]){ // prints the current timestamp with UTC as time zone Instant currTimeStamp = Instant.now(); System.out.println("Instant timestamp is: "+ currTimeStamp); // prints the number of seconds as Unix timestamp from epoch time System.out.println("Number of seconds elapsed: " + currTimeStamp.getEpochSecond()); // prints the Unix timestamp in milliseconds System.out.println("Number of milliseconds elapsed: " + currTimeStamp.toEpochMilli()); } } Instant timestamp is: 2015-11-02T03:16:04.502Z Number of seconds elapsed: 1446434164 Number of milliseconds elapsed: 1446434164502
  • 131. java.time.Period LocalDate manufacturingDate = LocalDate.of(2016, Month.JANUARY, 1); LocalDate expiryDate = LocalDate.of(2018, Month.JULY, 18); Period expiry = Period.between(manufacturingDate, expiryDate); System.out.printf("Medicine will expire in: %d years, %d months, and %d days (%s)n", expiry.getYears(), expiry.getMonths(), expiry.getDays(), expiry); Medicine will expire in: 2 years, 6 months, and 17 days (P2Y6M17D)
  • 133. The Java 8 date and time API differentiates how humans and computers use date- and time-related information. For example, the Instant class represents a Unix timestamp and internally uses long and int variables. Instant values are not very readable or usable by humans because the class does not support methods related to day, month, hours, and so on (in contrast, the Period class supports such methods).
  • 134. java.time.Duration LocalDateTime comingMidnight = LocalDateTime.of(LocalDate.now().plusDays(1), LocalTime.MIDNIGHT); LocalDateTime now = LocalDateTime.now(); Duration between = Duration.between(now, comingMidnight); System.out.println(between); PT7H13M42.003S
  • 135. Important Methods in Duration
  • 136. Summary of Instant, Period and Duration
  • 137. TemporalUnit import java.time.temporal.ChronoUnit; public class ChronoUnitValues { public static void main(String []args) { System.out.println("ChronoUnit DateBased TimeBased Duration"); System.out.println("---------------------------------------"); for(ChronoUnit unit : ChronoUnit.values()) { System.out.printf("%10s t %b tt %b tt %s %n”, unit, unit.isDateBased(), unit.isTimeBased(), unit.getDuration()); } } }
  • 138.
  • 139. ZoneId System.out.println("My zone id is: " + ZoneId.systemDefault()); My zone id is: Asia/Kolkata ZoneId AsiaKolkataZoneId = ZoneId.of("Asia/Kolkata");
  • 140. ZonedDateTime LocalDate currentDate = LocalDate.now(); LocalTime currentTime = LocalTime.now(); ZoneId myZone = ZoneId.systemDefault(); ZonedDateTime zonedDateTime = ZonedDateTime.of(currentDate, currentTime, myZone); System.out.println(zonedDateTime); 2015-11-05T11:38:40.647+05:30[Asia/Kolkata]
  • 141. ZonedDateTime ZoneId myZone = ZoneId.of("Asia/Kolkata"); LocalDateTime dateTime = LocalDateTime.now(); ZonedDateTime zonedDateTime = dateTime.atZone(myZone); ZoneOffset zoneOffset = zonedDateTime.getOffset(); System.out.println(zoneOffset); +05:30
  • 142. ZonedDateTime ZoneId singaporeZone = ZoneId.of(“Asia/Singapore"); ZonedDateTime dateTimeInSingapore = ZonedDateTime.of(LocalDateTime.of(2016, Month.JANUARY, 1, 6, 0), singaporeZone); ZoneId aucklandZone = ZoneId.of("Pacific/Auckland"); ZonedDateTime sameDateTimeInAuckland = dateTimeInSingapore.withZoneSameInstant(aucklandZone); Duration timeDifference = Duration.between( dateTimeInSingapore.toLocalTime(), sameDateTimeInAuckland.toLocalTime()); System.out.printf("Time difference between %s and %s zones is %d hours”, singaporeZone, aucklandZone, timeDifference.toHours()); Time difference between Asia/Singapore and Pacific/Auckland zones is 5 hours
  • 143. Daylight Savings ZoneId kolkataZone = ZoneId.of("Asia/Kolkata"); Duration kolkataDST = kolkataZone.getRules().getDaylightSavings(Instant.now()); System.out.printf("Kolkata zone DST is: %d hours %n", kolkataDST.toHours()); ZoneId aucklandZone = ZoneId.of("Pacific/Auckland"); Duration aucklandDST = aucklandZone.getRules().getDaylightSavings(Instant.now()); System.out.printf("Auckland zone DST is: %d hours", aucklandDST.toHours()); Kolkata zone DST is: 0 hours Auckland zone DST is: 1 hours
  • 144. DateTimeFormatter Predefined formatters: • ISO_DATE (2015-11-05) • ISO_TIME (11:25:47.624) • RFC_1123_DATE_TIME (Thu, 5 Nov 2015 11:27:22 +0530) • ISO_ZONED_DATE_TIME (2015-11-05T11:30:33.49+05:30[Asia/Kolkata])
  • 145. DateTimeFormatter Wake up time: 06:00:00 LocalTime wakeupTime = LocalTime.of(6, 0, 0); System.out.println("Wake up time: " + DateTimeFormatter.ISO_TIME.format(wakeupTime)); 01 Jan 2016 DateTimeFormatter customFormat = DateTimeFormatter.ofPattern("dd MMM yyyy"); System.out.println(customFormat.format(LocalDate.of(2016, Month.JANUARY, 01)));
  • 146. Uppercase and lowercase letters can have similar or different meanings when used in format strings for dates and times. Read the Javadoc for these patterns carefully before trying to use these letters. For example, in dd-MM-yy, MM refers to month; however, in dd-mm- yy, mm refers to minutes !
  • 147. Formatting Dates • G (era: BC, AD) • y (year of era: 2015, 15) • Y (week-based year: 2015, 15) • M (month: 11, Nov, November) • w (week in year: 13) • W (week in month: 2) • E (day name in week: Sun, Sunday) • D (day of year: 256) • d (day of month: 13)
  • 148. Custom Date Patterns public class CustomDatePatterns { public static void main(String []args) { // patterns from simple to complex ones String [] dateTimeFormats = { "dd-MM-yyyy", /* d is day (in month), M is month, y is year */ "d '('E')' MMM, YYYY", /*E is name of the day (in week), Y is year*/ "w'th week of' YYYY", /* w is the week of the year */ "EEEE, dd'th' MMMM, YYYY" /*E is day name in the week */ }; LocalDateTime now = LocalDateTime.now(); for(String dateTimeFormat : dateTimeFormats) { System.out.printf("Pattern "%s" is %s %n", dateTimeFormat, DateTimeFormatter.ofPattern(dateTimeFormat).format(now)); } } } Pattern "dd-MM-yyyy" is 05-11-2015 Pattern "d '('E')' MMM, YYYY" is 5 (Thu) Nov, 2015 Pattern "w'th week of' YYYY" is 45th week of 2015 Pattern "EEEE, dd'th' MMMM, YYYY" is Thursday, 05th November, 2015
  • 149. Formatting Times • a (marker for the text a.m./p.m. marker) • H (hour: value range 0–23) • k (hour: value range 1–24) • K (hour in a.m./p.m.: value range 0–11) • h (hour in a.m./p.m.: value range 1–12) • m (minute) • s (second) • S (fraction of a second) • z (time zone: general time-zone format)
  • 150. Custom Time Patterns class CustomTimePatterns { public static void main(String []args) { // patterns from simple to complex ones String [] timeFormats = { "h:mm", /* h is hour in am/pm (1-12), m is minute */ "hh 'o''clock'", /* '' is the escape sequence to print a single quote */ "H:mm a", /* H is hour in day (0-23), a is am/pm*/ "hh:mm:ss:SS", /* s is seconds, S is milliseconds */ "K:mm:ss a" /* K is hour in am/pm(0-11) */ }; LocalTime now = LocalTime.now(); for(String timeFormat : timeFormats) { System.out.printf("Time in pattern "%s" is %s %n", timeFormat, DateTimeFormatter.ofPattern(timeFormat).format(now)); } } } Time in pattern "h:mm" is 12:27 Time in pattern "hh 'o''clock'" is 12 o'clock Time in pattern "H:mm a" is 12:27 PM Time in pattern "hh:mm:ss:SS" is 12:27:10:41 Time in pattern "K:mm:ss a" is 0:27:10 PM
  • 151. Flight Travel - Time Calculation - Example DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd MMM yyyy hh.mm a"); // Leaving on 1st Jan 2016, 6:00am from "Singapore" ZonedDateTime departure = ZonedDateTime.of( LocalDateTime.of(2016, Month.JANUARY, 1, 6, 0), ZoneId.of("Asia/Singapore")); System.out.println("Departure: " + dateTimeFormatter.format(departure)); // Arrival on the same day in 10 hours in "Auckland" ZonedDateTime arrival = departure.withZoneSameInstant(ZoneId.of("Pacific/Auckland")).plusHours(10); System.out.println("Arrival: " + dateTimeFormatter.format(arrival)); Departure: 01 Jan 2016 06.00 AM Arrival: 01 Jan 2016 09.00 PM
  • 152. Agenda • Introduction & Overview • Lambdas • Functional interfaces • Streams • Parallel streams • Date & Time package • Refactoring to Java 8
  • 153. Examples of refactorings (to Java 8) ❖ Convert anonymous inner classes to lambda expressions (when they are functional interfaces) ❖ Convert for/foreach loops to streams (i.e., external iteration to internal iteration)
  • 154. Refactoring loops to streams ❖ Replace if conditions with ‘filter’ and calls to methods that return a boolean value (Predicate) ❖ Replace accumulation operations with reduce (or its special forms like sum, count, etc).
  • 155. Source: LAMBDAFICATOR: From Imperative to Functional Programming through Automated Refactoring. Lyle Franklin; Alex Gyori; Jan Lahoda; Danny Dig. 35th International Conference on Software Engineering (ICSE), 2013.
  • 156. Tool support for refactoring ❖ Most Java IDEs provide suggestions to automatically refactor to lambdas and streams ❖ IDEs that support Java 8 refactoring include: Eclipse, IntelliJ Idea and NetBeans
  • 157. Refactoring suggestions in Netbeans Image source: http://refactoring.info/tools/LambdaFicator/
  • 158. Java 8 Migration Aids in IntelliJ IDEA Image source: https://www.jetbrains.com/help/img/idea/ij_java_8_inspection_results_migration_runnable.png
  • 159. Java 8 Refactorings in IntelliJ IDEA Image source: https://www.jetbrains.com/help/img/idea/ij_java_8_replace_method_reference_with_lambda.png https://www.jetbrains.com/help/img/idea/ij_java_8_can_be_replaced_with_method_ref.png
  • 160. Refactoring suggestions in Netbeans Image source: http://refactoring.info/tools/LambdaFicator/
  • 161. Refactoring suggestions in Netbeans Image source: http://refactoring.info/tools/LambdaFicator/
  • 162. Suggested Reading ❖ Refactoring with Loops and Collection Pipelines (Martin Fowler, 2015) ❖ Pragmatic Functional Refactoring with Java 8 (Raoul- Gabriel Urma & Richard Warburton, 2015) ❖ Migrating to Java 8 (IntelliJ IDEA, 2016)
  • 164.
  • 165. Image credits ❖ http://mayhemandmuse.com/wp-content/uploads/2013/04/This-optical-illusion-drawing-by-WE- Hill-shows-both-his-wife-and-his-mother-in-law.jpg ❖ http://www.webtrafficroi.com/wp-content/uploads/2012/10/mahatma-gandhi-apple-think- different.jpg ❖ http://rexx-language-association-forum.44760.x6.nabble.com/file/n2236/Ruby-lambda-function.jpg ❖ http://www.ibm.com/developerworks/library/j-jn16/figure1.png ❖ http://www.ibm.com/developerworks/library/j-jn16/figure2.png ❖ http://img.viralpatel.net/2014/01/java-lambda-expression.png ❖ http://www.codercaste.com/wp-content/uploads/2011/01/animals.png ❖ http://blog.takipi.com/wp-content/uploads/2014/03/blog_lambada_2.png ❖ http://quotespictures.com/wp-content/uploads/2014/01/it-is-not-the-strongest-of-the-species-that- survive-nor-the-most-intelligent-but-the-one-most-responsive-to-change-charles-darwin.jpg ❖ http://7-themes.com/data_images/out/27/6859733-surfing-wallpaper.jpg