SlideShare a Scribd company logo
1 of 93
Download to read offline
Productive
Programming
in Java 8
Covering Lambdas and Streams
ocpjava.wordpress.com
Ganesh Samarthyam (ganesh.samarthyam@gmail.com)
❖ Programming examples are
from our book:
❖ Oracle Certified
Professional Java SE 8
Programmer Exam 1Z0-809:
A Comprehensive OCPJP 8
Certification Guide, S.G.
Ganesh, Hari Kiran Kumar,
Tushar Sharma, Apress, 2016.
❖ Website: ocpjava.wordpress.com
Java
876
…
I am evolving…
Java 8: Latest (red-hot)
Recent addition:
lambdas
8
Greek characters
are scary!
He he, but lambdas
are fun, not scary
Java meets functional
programming (with lambdas)
How different is lambdas?
if
while
for
switch
Introducing our star
feature - lambda
functions
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 lambdas?
❖ (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
❖ Functions don’t change external state
Arrays.asList("eeny", "meeny", "miny", “mo”)
.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
Lambda
expression
You can use lambdas for
some amazing stuff
sediment
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
So, lets get our hands dirty
and start coding
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
@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
Old functional interfaces
// 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); }
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
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
arg -> System.out.println(arg)
System.out::println
Method references - “syntactic sugar” for
lambda functions
They “route” function parameters
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));
Using built-in functional interfaces
Built-in functional interfaces are
a part of the java.util.function
package (in Java 8)
Using built-in functional 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 givenConsumer<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 inFunction<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.
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) statements for our
understanding
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
Parallel Streams
race conditions
deadlocks
I really really hate
concurrency problems
Parallel code
Serial code
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
Adapt, learn functional
programming!
SOLID Principles
and Design Patterns
Bootcamp - 25 JUN 2016 - Bangalore
Register here: https://www.townscript.com/e/designpattern
Fee Rs. 3500
Discount (Rs. 500)
code: “First10”
Image credits
• http://www.wetplanetwhitewater.com/images/uploads/adam_mills_elliott82.jpg
• http://s.ecrater.com/stores/321182/53e46c705f68d_321182b.jpg
• http://img.viralpatel.net/2014/01/java-lambda-expression.png
• https://i.ytimg.com/vi/3C0R_fEXcYA/maxresdefault.jpg
• http://farm1.static.flickr.com/74/170765090_53762a686c.jpg
• http://www.monazu.com/wp-content/uploads/2012/06/ask-the-right-questions.jpg
• https://s-media-cache-ak0.pinimg.com/736x/43/42/8a/43428ac2c352166374d851e895ed5db1.jpg
• http://cdn.attackofthecute.com/August-17-2011-12-36-23-peekaboo-
kitty-46f32anul-131384-530-410.jpeg
• https://ludchurchmyblog.files.wordpress.com/2010/02/myths-legend-pictures-083.jpg
• http://www.youramazingplaces.com/wp-content/uploads/2013/06/Mauvoisin-Dam-
Switzerland-620x413.jpg
• http://www.welikeviral.com/files/2014/08/Image-914.jpg
• http://geekandpoke.typepad.com/.a/6a00d8341d3df553ef013485f6be4d970c-800wi
• https://qph.fs.quoracdn.net/main-qimg-56547c0506050206b50b80a268bf2a84
• https://i.ytimg.com/vi/kCVsKsgVhBA/maxresdefault.jpg
• http://i.livescience.com/images/i/000/022/395/original/man-dreams-bed.jpg
• https://static-secure.guim.co.uk/sys-images/Guardian/Pix/pictures/2012/11/26/1353952826063/Alarm-
clock-010.jpg
email sgganesh@gmail.com
website www.designsmells.com
twitter @GSamarthyam
linkedin bit.ly/sgganesh
slideshare slideshare.net/sgganesh

More Related Content

What's hot

What's hot (20)

Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Java8
Java8Java8
Java8
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
 
OCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertionsOCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertions
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
Smart Migration to JDK 8
Smart Migration to JDK 8Smart Migration to JDK 8
Smart Migration to JDK 8
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8
 

Similar to Productive Programming in Java 8 - with Lambdas and Streams

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
 
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
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
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
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
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
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8 Dori Waldman
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...Akaks
 
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJosé Paumard
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxBruceLee275640
 

Similar to Productive Programming in Java 8 - with Lambdas and Streams (20)

Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
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
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
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
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
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
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
Java
JavaJava
Java
 
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 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)
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
 
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
 

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

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
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
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
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.
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
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
 
(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
 
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
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.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
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
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
 

Recently uploaded (20)

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
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
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
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...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
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)
 
(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...
 
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
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
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...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.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
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
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...
 

Productive Programming in Java 8 - with Lambdas and Streams

  • 1. Productive Programming in Java 8 Covering Lambdas and Streams ocpjava.wordpress.com Ganesh Samarthyam (ganesh.samarthyam@gmail.com)
  • 2. ❖ Programming examples are from our book: ❖ Oracle Certified Professional Java SE 8 Programmer Exam 1Z0-809: A Comprehensive OCPJP 8 Certification Guide, S.G. Ganesh, Hari Kiran Kumar, Tushar Sharma, Apress, 2016. ❖ Website: ocpjava.wordpress.com
  • 4. Java 8: Latest (red-hot)
  • 7. He he, but lambdas are fun, not scary
  • 9. How different is lambdas? if while for switch
  • 10. Introducing our star feature - lambda functions
  • 11. List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); Consumer<String> printString = string -> System.out.println(string); strings.forEach(printString); Lambda functions!
  • 13. Lambdas is just a fancy name for functions without a name!
  • 14. What are lambdas? ❖ (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 ❖ Functions don’t change external state
  • 15. Arrays.asList("eeny", "meeny", "miny", “mo”) .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 Lambda expression
  • 16. You can use lambdas for some amazing stuff
  • 17. sediment pre- carbon ultra-filter post- carbon Filtered water E.g., you can compose lambda functions as in pipes-and-filters
  • 18. $ 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.
  • 19. $ 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
  • 20. 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
  • 21. Lambdas & streams help in productive programming!
  • 22. 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
  • 23. So, lets get our hands dirty and start coding
  • 24. 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
  • 25. @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
  • 26. Old functional interfaces // 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); }
  • 27. 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()); } }
  • 29. 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
  • 30. 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
  • 31. 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”
  • 32. 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
  • 33. arg -> System.out.println(arg) System.out::println Method references - “syntactic sugar” for lambda functions They “route” function parameters
  • 34. 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));
  • 36. Built-in functional interfaces are a part of the java.util.function package (in Java 8)
  • 37. Using built-in functional 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 givenConsumer<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 inFunction<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.
  • 38. 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)
  • 40. 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 }
  • 41. 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
  • 42. 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
  • 43. Consumer interface Stream.of("hello", "world") .forEach(System.out::println); // void forEach(Consumer<? super T> action); Prints: hello world
  • 45. 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 }
  • 46. Consumer interface: Example Consumer<String> printUpperCase = str -> System.out.println(str.toUpperCase()); printUpperCase.accept("hello"); Prints: HELLO
  • 47. 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
  • 48. 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
  • 50. 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 }
  • 51. Function interface: example Function<String, Integer> strLength = str -> str.length(); System.out.println(strLength.apply("supercalifragilisticexpialidocious")); Prints: 34
  • 52. 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
  • 53. 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
  • 55. 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 }
  • 56. Supplier interface: example Supplier<String> currentDateTime = () -> LocalDateTime.now().toString(); System.out.println(currentDateTime.get()); Prints current time: 2015-10-16T12:40:55.164
  • 57. 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.
  • 58.
  • 59. Java 8 streams (and parallel streams): Excellent example of applying functional programming in practice
  • 60. But what are streams?
  • 62. 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) statements for our understanding
  • 65. IntStream.range(1, 6) You can use range or iterate factory methods in the IntStream interface IntStream.iterate(1, i -> i + 1).limit(5)
  • 66. 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
  • 67. 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
  • 68. stream can be infinite IntStream.iterate(0, i -> i + 2).forEach(System.out::println); This code creates infinite stream of even numbers!
  • 69. IntStream .iterate(0, i -> i + 2) .limit(5) .forEach(System.out::println); Using the “limit” function to limit the stream to 5 integers
  • 70. 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
  • 72. Files.lines(Paths.get("FileRead.java")).forEach(System.out::println); This code prints the contents of the file “FileRead.java” in the current directory
  • 73. 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
  • 74. new Random().ints().limit(5).forEach(System.out::println); Generates 5 random integers and prints them on the console
  • 75. "hello".chars().sorted().forEach(ch -> System.out.printf("%c ", ch)); Extracts characters in the string “hello”, sorts the chars and prints the chars
  • 78.
  • 80.
  • 81. I really really hate concurrency problems
  • 83. long numOfPrimes = LongStream.rangeClosed(2, 100_000) .filter(PrimeNumbers::isPrime) .count(); System.out.println(numOfPrimes); Prints 9592 2.510 seconds
  • 84. Parallel code Serial code Let’s flip the switch by calling parallel() function
  • 85. long numOfPrimes = LongStream.rangeClosed(2, 100_000) .parallel() .filter(PrimeNumbers::isPrime) .count(); System.out.println(numOfPrimes); Prints 9592 1.235 seconds
  • 86. Wow! That’s an awesome flip switch!
  • 87. Internally, parallel streams make use of fork-join framework
  • 88.
  • 89. 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
  • 91. SOLID Principles and Design Patterns Bootcamp - 25 JUN 2016 - Bangalore Register here: https://www.townscript.com/e/designpattern Fee Rs. 3500 Discount (Rs. 500) code: “First10”
  • 92. Image credits • http://www.wetplanetwhitewater.com/images/uploads/adam_mills_elliott82.jpg • http://s.ecrater.com/stores/321182/53e46c705f68d_321182b.jpg • http://img.viralpatel.net/2014/01/java-lambda-expression.png • https://i.ytimg.com/vi/3C0R_fEXcYA/maxresdefault.jpg • http://farm1.static.flickr.com/74/170765090_53762a686c.jpg • http://www.monazu.com/wp-content/uploads/2012/06/ask-the-right-questions.jpg • https://s-media-cache-ak0.pinimg.com/736x/43/42/8a/43428ac2c352166374d851e895ed5db1.jpg • http://cdn.attackofthecute.com/August-17-2011-12-36-23-peekaboo- kitty-46f32anul-131384-530-410.jpeg • https://ludchurchmyblog.files.wordpress.com/2010/02/myths-legend-pictures-083.jpg • http://www.youramazingplaces.com/wp-content/uploads/2013/06/Mauvoisin-Dam- Switzerland-620x413.jpg • http://www.welikeviral.com/files/2014/08/Image-914.jpg • http://geekandpoke.typepad.com/.a/6a00d8341d3df553ef013485f6be4d970c-800wi • https://qph.fs.quoracdn.net/main-qimg-56547c0506050206b50b80a268bf2a84 • https://i.ytimg.com/vi/kCVsKsgVhBA/maxresdefault.jpg • http://i.livescience.com/images/i/000/022/395/original/man-dreams-bed.jpg • https://static-secure.guim.co.uk/sys-images/Guardian/Pix/pictures/2012/11/26/1353952826063/Alarm- clock-010.jpg
  • 93. email sgganesh@gmail.com website www.designsmells.com twitter @GSamarthyam linkedin bit.ly/sgganesh slideshare slideshare.net/sgganesh