SlideShare a Scribd company logo
Functional Thinking: Introduction to Lambdas
Ganesh Samarthyam
ganesh.samarthyam@gmail.com
www.designsmells.com
Adapt: Learn functional
programming
Functional Thinking - Programming with Lambdas in Java 8
Programming paradigms
Langauge
Paradigm
Declarative
Languages
Imperative
Languages
Logic
Languages
Functional
Languages
Procedural
Languages
Object-Oriented
Languages
e.g. Prolog e.g. Haskell e.g. C e.g. Java
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
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
Lambdas
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
Consumer<String> printString = string -> System.out.println(string);
strings.forEach(printString);
Lambda
functions!
Lambdas
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
Consumer<String> printString = string -> System.out.println(string);
strings.forEach(printString);
Capture in a
variable
Execute later
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.”
Functional languages
Haskell
Common Lisp
Scheme
Clojure
F#
OCaml
Erlang Hope
Scala
R
Languages that support functional programming
C# (3.0)
Python
JavaScript
D
Fortran 95
Visual Basic
PHP Java (8)
C++11
Lambdas added in Java 8
“Success is very largely a matter of adjusting one's self to the
ever-varying and changing environments of life”
- Napoleon Hill
Popular Languages
http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
Popular Languages
http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
Productive programming with lambdas
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()	}
Workshop overview
❖ Assumes that you already
know Java
❖ You’ll know how to use Java 8
lambdas and streams after this
session
❖ Try out the programs in your
machine
Lambdas in Java 8
Code examples & images from my upcoming book:
Oracle Certified Professional Java SE 8 Programmer Exam
1Z0-809 by S G Ganesh, Hari Kiran Kumar and Tushar Sharma,
Apress, December 2015
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
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
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));
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
One-liner #1
Files.lines(Paths.get("FileRead.java")).forEach(System.out::println);
This code prints the contents of
the file “FileRead.java” in the
current directory
One-liner #2
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
One-liner #3
new Random().ints().limit(5).forEach(System.out::println);
Generates 5 random integers and prints
them on the console
One-liner #4
"hello".chars().sorted().forEach(ch -> System.out.printf("%c ", ch));
Extracts characters in the string “hello”,
sorts the chars and prints the chars
Stream API
First stream example
"hello".chars().sorted().forEach(ch -> System.out.printf("%c ", ch));
The chars() method in String
results in a Stream; sorted() sorts
the entries in the stream
// prints e h l l o
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()
Stream pipeline example
Arrays.stream(Object.class.getMethods()) // source
.map(method -> method.getName()) // intermediate op
.distinct() // intermediate op
.forEach(System.out::println); // terminal operation
Stream pipeline example
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);
Stream pipeline illustration
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();
Stream sources
IntStream.range(1, 6)
You can use range or iterate
factory methods in the
IntStream interface
IntStream.iterate(1, i -> i + 1).limit(5)
Stream sources
Arrays.stream(new int[] {1, 2, 3, 4, 5})
Arrays.stream(new Integer[] {1, 2, 3, 4, 5})
You can use the stream() method in
java.util.Arrays class to create a
stream from a given array
Stream sources
Stream.of(1, 2, 3, 4, 5)
Stream.of(new Integer[]{1, 2, 3, 4, 5})
We can also create streams using factories
and builders (e..g, of() and build() methods
in the Stream interface)
Stream.builder().add(1).add(2).add(3).add(4).add(5).build()
Stream sources
• The lines() method in java.nio.file.Files class
• The splitAsStream() method in java.util.regex.Pattern class
• The ints() method in java.util.Random class
• The chars() method in java.lang.String class
There are numerous classes/interfaces in
the Java library that return a stream
Intermediate operations
Stream<T> filter(Predicate<? super T>
check) Removes the elements for which the check predicate returns false.
<R> Stream<R> map(Function<? super T,?
extends R> transform)
Applies the transform() function for each of the elements in the
stream.
Stream<T> distinct() Removes duplicate elements in the stream; it uses the equals()
method to determine if an element is repeated in the stream.
Stream<T> sorted()
Stream<T> sorted(Comparator<? super T>
compare)
Sorts the elements in its natural order. The overloaded version takes
a Comparator – you can pass a lambda function for that.
Stream<T> peek(Consumer<? super T>
consume)
Returns the same elements in the stream, but also executes the
passed consume lambda expression on the elements.
Stream<T> limit(long size)
Removes the elements if there are more elements than the given
size in the stream.
Terminal operations
void forEach(Consumer<?
super T> action)
Calls the action for every element in the
stream.
Object[] toArray()
Returns an Object array that has the elements
in the stream.
Optional<T> min(Comparator<?
super T> compare)
Returns the minimum value in the stream
(compares the objects using the given compare
function).
Optional<T> max(Comparator<?
super T> compare)
Returns the maximum value in the stream
(compares the objects using the given compare
function).
long count() Returns the number of elements in the stream.
Using “range” instead of “for” loop
IntStream.range(1, 10).map(i -> i * i).forEach(System.out::println);
Using streams instead of imperative for i = 1 to 1, print i * i
Prints:
1
4
9
16
25
36
49
64
81
“Mapping” elements in a stream
1	 	2 	3 	4 	5	
1	 	4 	9 	16 		25	
map(i	->	i	*	i)
Streams can be “infinite”
“Generating” even numbers
IntStream.iterate(0, i -> i + 2).forEach(System.out::println);
The problem is it creates infinite number of even numbers!
“Generating” limited 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
“Generating” limited even numbers
IntStream
.iterate(0, i -> i + 1)
.filter(i -> (i % 2) == 0)
.limit(5)
.forEach(System.out::println);
You can also use the “filter” method
“Reduction” using “sum” function
System.out.println(IntStream.rangeClosed(0, 10).sum());
Sum of integers from 1 to 10 using “implicit reduction”
“Reduction” using “sum” function
System.out.println(
IntStream
.rangeClosed(1, 5)
.reduce((x, y) -> (x * y))
.getAsInt());
Factorial of 5 using “explicit reduce”
Using “map” function
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
strings.stream().map(value -> value.toUpperCase()).forEach(System.out::println);
public static void printUpperCaseString(String string) {
System.out.println(string.toUpperCase());
}
strings.forEach(MethodReference::printUpperCaseString);
Using “collect” function
String boxedString =
Arrays
.asList("eeny", "meeny", "miny", "mo")
.stream()
.collect(Collectors.joining(“ ,", "[", "]"));
System.out.println(boxedString);
Prints: [eeny, meeny, miny, mo]
Using Files.list()
Files.list(Paths.get("."))
.map(path -> path.toAbsolutePath())
.forEach(System.out::println);
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.
Built-in interfaces
Streams are “lazy”
Cannot “reuse” a stream!
Important stream interfaces
<<interface>>	
java.u0l.stream.BaseStream	
<<interface>>	
java.u0l.stream.IntStream	
<<interface>>	
java.u0l.stream.LongStream	
<<interface>>	
java.u0l.stream.DoubleStream	
<<interface>>	
java.u0l.stream.Stream<T>
map vs. flatMap methods
1	 	2 	3 	4 	5	
1	 	4 	9 	16 		25	
map(i	->	i	*	i)	
1	 	3 	5	
1	 	3 	5 	2 		4	
flatMap(ints	->	ints.stream())	
2 	4
		
sorted()	
1	 	2 	3 	4 	5	
1	 	4 	9 	16 		25	
map(i	->	i	*	i)
String limerick = "There was a young lady named Bright " +
"who traveled much faster than light " +
"She set out one day " +
"in a relative way " +
"and came back the previous night ";
IntSummaryStatistics wordStatistics =
Pattern.compile(" ")
.splitAsStream(limerick)
.mapToInt(word -> word.length())
.summaryStatistics();
System.out.printf(" Number of words = %d n Sum of the length of the words = %d n" +
" Minimum word size = %d n Maximum word size %d n " +
" Average word size = %f n", wordStatistics.getCount(),
wordStatistics.getSum(), wordStatistics.getMin(),
wordStatistics.getMax(), wordStatistics.getAverage());
Data calculation methods in stream
Parallel streams
Threading problems
Threading problems
Fork-join framework
forkJoinAlgorithm() {
fork (split) the tasks;
join the tasks;
compose the results;
}
doRecursiveTask(input) {
if (the task is small enough to be handled by a thread) {
compute the small task;
if there is a result to return, do so
}
else {
divide (i.e., fork) the task into two parts
call compute() on first task, join() on second task, return combined results
}
}
Fork-join framework
Stream - for primes
import java.util.stream.LongStream;
class PrimeNumbers {
private static boolean isPrime(long val) {
for(long i = 2; i <= val/2; i++) {
if((val % i) == 0) {
return false;
}
}
return true;
}
public static void main(String []args) {
long numOfPrimes = LongStream.rangeClosed(2, 100_000)
.filter(PrimeNumbers::isPrime)
.count();
System.out.println(numOfPrimes);
}
}
Stream - for primes
import java.util.stream.LongStream;
class PrimeNumbers {
private static boolean isPrime(long val) {
for(long i = 2; i <= val/2; i++) {
if((val % i) == 0) {
return false;
}
}
return true;
}
public static void main(String []args) {
long numOfPrimes = LongStream.rangeClosed(2, 100_000)
.parallel()
.filter(PrimeNumbers::isPrime)
.count();
System.out.println(numOfPrimes);
}
}
Be careful with parallel streams
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);
}
}
Functional Thinking - Programming with Lambdas in Java 8
Adapt: Learn functional
programming
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
Functional Thinking - Programming with Lambdas in Java 8
Ad

More Related Content

What's hot (20)

Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
Andrzej Grzesik
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
Jim Bethancourt
 
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
CodeOps Technologies LLP
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
Tobias Coetzee
 
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
Ganesh Samarthyam
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
Jussi Pohjolainen
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
NexThoughts Technologies
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
Manav Prasad
 
Java8 features
Java8 featuresJava8 features
Java8 features
Elias Hasnat
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
Venkata Naga Ravi
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
Stephen Colebourne
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Hyderabad Scalability Meetup
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
Jussi Pohjolainen
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
Logan Chien
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
NewCircle Training
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습
DoHyun Jung
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8
James Brown
 
Java8
Java8Java8
Java8
Felipe Mamud
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
Manav Prasad
 

Similar to Functional Thinking - Programming with Lambdas in Java 8 (20)

Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
KonfHubTechConferenc
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
Ganesh Samarthyam
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
Sandeep Kr. Singh
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
Philip Johnson
 
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
Henri Tremblay
 
RESTful Web Services with Jersey
RESTful Web Services with JerseyRESTful Web Services with Jersey
RESTful Web Services with Jersey
Scott Leberknight
 
Slides
SlidesSlides
Slides
Videoguy
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
Aniket Thakur
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
Sharon Rozinsky
 
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxLab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
smile790243
 
FUNctional Programming in Java 8
FUNctional Programming in Java 8FUNctional Programming in Java 8
FUNctional Programming in Java 8
Richard Walker
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
Esther Lozano
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshots
richambra
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
Intro C# Book
 
Java8.part2
Java8.part2Java8.part2
Java8.part2
Ivan Ivanov
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018
Codemotion
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
J On The Beach
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
Nicola Pedot
 
Lazy java
Lazy javaLazy java
Lazy java
Mario Fusco
 
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
KonfHubTechConferenc
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
Philip Johnson
 
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
Henri Tremblay
 
RESTful Web Services with Jersey
RESTful Web Services with JerseyRESTful Web Services with Jersey
RESTful Web Services with Jersey
Scott Leberknight
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
Sharon Rozinsky
 
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxLab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
smile790243
 
FUNctional Programming in Java 8
FUNctional Programming in Java 8FUNctional Programming in Java 8
FUNctional Programming in Java 8
Richard Walker
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
Esther Lozano
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshots
richambra
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
Intro C# Book
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018
Codemotion
 
Ad

More from Ganesh Samarthyam (20)

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
Ganesh Samarthyam
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
Ganesh Samarthyam
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
Ganesh 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 Enough
Ganesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
Ganesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
Ganesh 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 Deck
Ganesh 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 Language
Ganesh 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 Questions
Ganesh Samarthyam
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
Ganesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
Ganesh Samarthyam
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
Ganesh 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 quiz
Ganesh Samarthyam
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
Ganesh 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 Enough
Ganesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
Ganesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
Ganesh 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 Deck
Ganesh 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 Language
Ganesh 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 Questions
Ganesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
Ganesh 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 quiz
Ganesh Samarthyam
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
Ad

Recently uploaded (20)

Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Sales Deck SentinelOne Singularity Platform.pptx
Sales Deck SentinelOne Singularity Platform.pptxSales Deck SentinelOne Singularity Platform.pptx
Sales Deck SentinelOne Singularity Platform.pptx
EliandoLawnote
 
Xforce Keygen 64-bit AutoCAD 2025 Crack
Xforce Keygen 64-bit AutoCAD 2025  CrackXforce Keygen 64-bit AutoCAD 2025  Crack
Xforce Keygen 64-bit AutoCAD 2025 Crack
usmanhidray
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Sales Deck SentinelOne Singularity Platform.pptx
Sales Deck SentinelOne Singularity Platform.pptxSales Deck SentinelOne Singularity Platform.pptx
Sales Deck SentinelOne Singularity Platform.pptx
EliandoLawnote
 
Xforce Keygen 64-bit AutoCAD 2025 Crack
Xforce Keygen 64-bit AutoCAD 2025  CrackXforce Keygen 64-bit AutoCAD 2025  Crack
Xforce Keygen 64-bit AutoCAD 2025 Crack
usmanhidray
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 

Functional Thinking - Programming with Lambdas in Java 8

  • 1. Functional Thinking: Introduction to Lambdas Ganesh Samarthyam [email protected] www.designsmells.com
  • 10. Perspective - for loops! List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); for(String string : strings) { System.out.println(string); } External Iteration
  • 11. Perspective - for loops! List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); strings.forEach(string -> System.out.println(string)); Internal Iteration
  • 12. 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
  • 13. 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
  • 14. Lambdas List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); Consumer<String> printString = string -> System.out.println(string); strings.forEach(printString); Lambda functions!
  • 15. Lambdas List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); Consumer<String> printString = string -> System.out.println(string); strings.forEach(printString); Capture in a variable Execute later
  • 16. 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
  • 17. 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.”
  • 19. Languages that support functional programming C# (3.0) Python JavaScript D Fortran 95 Visual Basic PHP Java (8) C++11
  • 21. “Success is very largely a matter of adjusting one's self to the ever-varying and changing environments of life” - Napoleon Hill
  • 24. Productive programming with lambdas 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() }
  • 25. Workshop overview ❖ Assumes that you already know Java ❖ You’ll know how to use Java 8 lambdas and streams after this session ❖ Try out the programs in your machine
  • 27. Code examples & images from my upcoming book: Oracle Certified Professional Java SE 8 Programmer Exam 1Z0-809 by S G Ganesh, Hari Kiran Kumar and Tushar Sharma, Apress, December 2015
  • 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(); } }
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. 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 }
  • 33. 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));
  • 34. Method references Method references - “syntactic sugar” for lambda functions They “route” function parameters arg -> System.out.println(arg) System.out::println
  • 35. 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);
  • 36. 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
  • 37. 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);
  • 38. “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”
  • 39. “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
  • 40. One-liner #1 Files.lines(Paths.get("FileRead.java")).forEach(System.out::println); This code prints the contents of the file “FileRead.java” in the current directory
  • 41. One-liner #2 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
  • 43. One-liner #4 "hello".chars().sorted().forEach(ch -> System.out.printf("%c ", ch)); Extracts characters in the string “hello”, sorts the chars and prints the chars
  • 45. First stream example "hello".chars().sorted().forEach(ch -> System.out.printf("%c ", ch)); The chars() method in String results in a Stream; sorted() sorts the entries in the stream // prints e h l l o
  • 47. Stream pipeline example Arrays.stream(Object.class.getMethods()) // source .map(method -> method.getName()) // intermediate op .distinct() // intermediate op .forEach(System.out::println); // terminal operation
  • 48. Stream pipeline example 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);
  • 50. Stream sources IntStream.range(1, 6) You can use range or iterate factory methods in the IntStream interface IntStream.iterate(1, i -> i + 1).limit(5)
  • 51. Stream sources Arrays.stream(new int[] {1, 2, 3, 4, 5}) Arrays.stream(new Integer[] {1, 2, 3, 4, 5}) You can use the stream() method in java.util.Arrays class to create a stream from a given array
  • 52. Stream sources Stream.of(1, 2, 3, 4, 5) Stream.of(new Integer[]{1, 2, 3, 4, 5}) We can also create streams using factories and builders (e..g, of() and build() methods in the Stream interface) Stream.builder().add(1).add(2).add(3).add(4).add(5).build()
  • 53. Stream sources • The lines() method in java.nio.file.Files class • The splitAsStream() method in java.util.regex.Pattern class • The ints() method in java.util.Random class • The chars() method in java.lang.String class There are numerous classes/interfaces in the Java library that return a stream
  • 54. Intermediate operations Stream<T> filter(Predicate<? super T> check) Removes the elements for which the check predicate returns false. <R> Stream<R> map(Function<? super T,? extends R> transform) Applies the transform() function for each of the elements in the stream. Stream<T> distinct() Removes duplicate elements in the stream; it uses the equals() method to determine if an element is repeated in the stream. Stream<T> sorted() Stream<T> sorted(Comparator<? super T> compare) Sorts the elements in its natural order. The overloaded version takes a Comparator – you can pass a lambda function for that. Stream<T> peek(Consumer<? super T> consume) Returns the same elements in the stream, but also executes the passed consume lambda expression on the elements. Stream<T> limit(long size) Removes the elements if there are more elements than the given size in the stream.
  • 55. Terminal operations void forEach(Consumer<? super T> action) Calls the action for every element in the stream. Object[] toArray() Returns an Object array that has the elements in the stream. Optional<T> min(Comparator<? super T> compare) Returns the minimum value in the stream (compares the objects using the given compare function). Optional<T> max(Comparator<? super T> compare) Returns the maximum value in the stream (compares the objects using the given compare function). long count() Returns the number of elements in the stream.
  • 56. Using “range” instead of “for” loop IntStream.range(1, 10).map(i -> i * i).forEach(System.out::println); Using streams instead of imperative for i = 1 to 1, print i * i Prints: 1 4 9 16 25 36 49 64 81
  • 57. “Mapping” elements in a stream 1 2 3 4 5 1 4 9 16 25 map(i -> i * i)
  • 58. Streams can be “infinite”
  • 59. “Generating” even numbers IntStream.iterate(0, i -> i + 2).forEach(System.out::println); The problem is it creates infinite number of even numbers!
  • 60. “Generating” limited 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
  • 61. “Generating” limited even numbers IntStream .iterate(0, i -> i + 1) .filter(i -> (i % 2) == 0) .limit(5) .forEach(System.out::println); You can also use the “filter” method
  • 62. “Reduction” using “sum” function System.out.println(IntStream.rangeClosed(0, 10).sum()); Sum of integers from 1 to 10 using “implicit reduction”
  • 63. “Reduction” using “sum” function System.out.println( IntStream .rangeClosed(1, 5) .reduce((x, y) -> (x * y)) .getAsInt()); Factorial of 5 using “explicit reduce”
  • 64. Using “map” function List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); strings.stream().map(value -> value.toUpperCase()).forEach(System.out::println); public static void printUpperCaseString(String string) { System.out.println(string.toUpperCase()); } strings.forEach(MethodReference::printUpperCaseString);
  • 65. Using “collect” function String boxedString = Arrays .asList("eeny", "meeny", "miny", "mo") .stream() .collect(Collectors.joining(“ ,", "[", "]")); System.out.println(boxedString); Prints: [eeny, meeny, miny, mo]
  • 66. Using Files.list() Files.list(Paths.get(".")) .map(path -> path.toAbsolutePath()) .forEach(System.out::println);
  • 67. 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.
  • 72. map vs. flatMap methods 1 2 3 4 5 1 4 9 16 25 map(i -> i * i) 1 3 5 1 3 5 2 4 flatMap(ints -> ints.stream()) 2 4 sorted() 1 2 3 4 5 1 4 9 16 25 map(i -> i * i)
  • 73. String limerick = "There was a young lady named Bright " + "who traveled much faster than light " + "She set out one day " + "in a relative way " + "and came back the previous night "; IntSummaryStatistics wordStatistics = Pattern.compile(" ") .splitAsStream(limerick) .mapToInt(word -> word.length()) .summaryStatistics(); System.out.printf(" Number of words = %d n Sum of the length of the words = %d n" + " Minimum word size = %d n Maximum word size %d n " + " Average word size = %f n", wordStatistics.getCount(), wordStatistics.getSum(), wordStatistics.getMin(), wordStatistics.getMax(), wordStatistics.getAverage()); Data calculation methods in stream
  • 77. Fork-join framework forkJoinAlgorithm() { fork (split) the tasks; join the tasks; compose the results; } doRecursiveTask(input) { if (the task is small enough to be handled by a thread) { compute the small task; if there is a result to return, do so } else { divide (i.e., fork) the task into two parts call compute() on first task, join() on second task, return combined results } }
  • 79. Stream - for primes import java.util.stream.LongStream; class PrimeNumbers { private static boolean isPrime(long val) { for(long i = 2; i <= val/2; i++) { if((val % i) == 0) { return false; } } return true; } public static void main(String []args) { long numOfPrimes = LongStream.rangeClosed(2, 100_000) .filter(PrimeNumbers::isPrime) .count(); System.out.println(numOfPrimes); } }
  • 80. Stream - for primes import java.util.stream.LongStream; class PrimeNumbers { private static boolean isPrime(long val) { for(long i = 2; i <= val/2; i++) { if((val % i) == 0) { return false; } } return true; } public static void main(String []args) { long numOfPrimes = LongStream.rangeClosed(2, 100_000) .parallel() .filter(PrimeNumbers::isPrime) .count(); System.out.println(numOfPrimes); } }
  • 81. Be careful with parallel streams 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); } }
  • 84. 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