c07 JSE Java8LamdaAndStreams
c07 JSE Java8LamdaAndStreams
summary of Java SE
presentation
Java Programming – Software App Development
Cristian Toma
1 2 3
Java 8 Features
& Prerequisites
Java 8 Lambda,
Meth o d Reference,
Fu n ctional Interface,
Streams
Exchange
Ideas
1
Lambda Expressions, Method References, Functional Interfaces, Default method, Stream API,
Anonymous, Inner classes, Call-back, Closure
Copyright: https://www.tutorialspoint.com/java8/index.htm
1. Java 8 Features
Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
1.1 Java 8 Nashorn JavaScript Engine
Java 8 JavaScript Nashorn Feature – Pre-requisite for Closure and Callbacks:
jjs
For Nashorn engine, JAVA 8 introduces a new command line
tool, jjs, to execute javascript codes at console.
//sample.js
print('Hello World!');
$jjs
jjs> quit()
>>
Copyright: https://www.tutorialspoint.com/java8/index.htm
1.1 Java 8 Nashorn JavaScript Engine
Java 8 JavaScript Nashorn Feature:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
try {
nashorn.eval("print('" + name + "')");
result = (Integer) nashorn.eval("10 + 2");
} catch(ScriptException e) {
System.out.println("Error executing script: "+ e.getMessage());
}
System.out.println(result.toString());
}
} Copyright: https://www.tutorialspoint.com/java8/index.htm
1.1 Java 8 Nashorn JavaScript Engine
Java 8 JavaScript Nashorn Feature:
import java.io.FileReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
The following example explains how to import and use Java classes in java
script −
//sampleBigDecimal.js
var BigDecimal = Java.type('java.math.BigDecimal');
return result.toPlainString();
}
b) Function CALL
Function Pointer
Function1
Data
Function2
d) RESULT
Copyright: https://en.wikipedia.org/wiki/Callback_(computer_programming)
1.1 Java 8 Nashorn JavaScript Engine
// define our function with the callback argument Closure is how the one is
function some_function1(arg1, arg2, callback) { building it, the callback is
// this generates a random number between how the one is using it.
// arg1 and arg2
var my_number = arg1 + arg2; A callback can be
// then we're done, so we'll call the callback and implemented (build):
// pass our result • as a closure (in
callback(my_number); languages that have
} them) or;
• an implementation of
function fcalled2(num) { an interface (in Java,
// this anonymous function will run when the as an anonymous
// callback is called inner class or a
print("callback called! " + num); regular class).
}
// define our function with the callback argument Closure is how the one is
function some_function(arg1, arg2, callback) { building it, the callback is
// this generates a random number between how the one is using it.
// arg1 and arg2
var my_number = arg1 + arg2; A callback can be
// then we're done, so we'll call the callback and implemented (build):
// pass our result • as a closure (in
callback(my_number); languages that have
} them) or;
• an implementation of
// call the function (callback usage) by closure implementation an interface (in Java,
some_function(5, 15, function(num) { as an anonymous
// this anonymous function will run when the inner class or a
// callback is called regular class).
print("callback called! " + num);
});
1.1 Java 8 Nashorn JavaScript Engine
Java POJO Callbacks!?:
Java inner class or nested class is a class i.e. declared inside the class or
interface.
We use inner classes to logically group classes and interfaces in one place
so that it can be more readable and maintainable.
Additionally, it can access all the members of outer class including private
data members and methods.
Advantage of java inner classes
Syntax of Inner class
There are basically three advantages of inner classes
class Java_Outer_class { in java. They are as follows:
//code 1) Nested classes represent a special type of
class Java_Inner_class { relationship that is it can access all the members
//code (data members and methods) of outer class including
} private.
} 2) Nested classes are used to develop more readable
and maintainable code because it logically group
classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.
Copyright: http://www.javatpoint.com/java-inner-class
1.2 Java Nested Classes
Copyright: http://www.javatpoint.com/java-inner-class
1.2 Java Inner Class
Java Member inner class
A non-static class that is created inside a class but outside a method is called
member inner class.
Syntax:
class Outer{
//code
class Inner{
//code
}
}
In this example, we are creating msg() method in member inner class that is accessing the private data
member of outer class.
class TestMemberOuter1 {
private int data=30;
class Inner {
void msg(){System.out.println("data is "+data);} //it will print 30
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
} Copyright: http://www.javatpoint.com/java-inner-class
1.2 Java Inner Class
Java Anonymous inner class
A class that have no name is known as anonymous inner class in java. It should be used if you have to
override method of class or interface. Java Anonymous inner class can be created by two ways:
• Class (may be abstract or concrete).
• Interface
Copyright: http://www.javatpoint.com/java-inner-class
1.2 Java Inner Class
Java Local inner class
A class i.e. created inside a method is called local inner class in Java. If you want to invoke the methods of
local inner class, you must instantiate this class inside the method.
Rules:
Local variable can't be private, public or protected.
Local inner class cannot be invoked from outside the method.
Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access the non-final local variable in
local inner class
Copyright: http://www.javatpoint.com/java-inner-class
1.2 Java Inner Class
Java static nested class
A static class i.e. created inside a class is called static nested class in java. It cannot
access non-static data members and methods. It can be accessed by outer class
name.
§ It can access static data members of outer class including private.
§ Static nested class cannot access non-static (instance) data member or method.
1. Java static nested class example with instance method
// If you have the static member inside static nested class, you don't
// need to create instance of static nested class.
Copyright: http://www.javatpoint.com/java-inner-class
1.2 Java Inner Class
Java Nested Interface
An interface i.e. declared within another interface or class is known as nested interface. The nested
interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface
must be referred by the outer interface or class. It can't be accessed directly.
There are given some points that should be remembered by the java programmer.
§ Nested interface must be public if it is declared inside the interface but it can have any access modifier
if declared within the class.
§ Nested interfaces are declared static implicitly.
Copyright: http://www.javatpoint.com/java-inner-class
1.2 Java Inner Class
Example of nested interface which is declared Example of nested interface which is declared
within the interface within the class
In this example, we are going to learn how to In this example, we see how can we define an
declare the nested interface and how we can interface inside the class and how can we access it.
access it.
Copyright: http://www.javatpoint.com/java-inner-class
1.2 Java Inner Class
You van use them sometimes as a syntax hack for Map instantiation:
To be clear, the first set of braces is the anonymous inner class (sub-classing
HashMap). The second set of braces is an instance initializer (rather than a
static one) which then sets the values on your HashMap subclass.
Copyright: https://stackoverflow.com/questions/355167/how-are-anonymous-inner-classes-used-in-java/40650596#40650596
1. Java Inner Class and Lambda Usage
When to Use Nested Classes, Local Classes, Anonymous Classes, and Lambda Expressions
As mentioned in the section Nested Classes, nested classes enable you to logically group classes that are
only used in one place, increase the use of encapsulation, and create more readable and maintainable code.
Local classes, anonymous classes, and lambda expressions also impart these advantages; however, they are
intended to be used for more specific situations:
• Local class: Use it if you need to create more than one instance of a class, access its constructor, or
introduce a new, named type (because, for example, you need to invoke additional methods later).
• Nested class: Use it if your requirements are similar to those of a local class, you want to make the type
more widely available, and you don't require access to local variables or method parameters.
• Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-
public fields and methods. Use a static nested class if you don't require this access.
• Lambda expression:
• Use it if you are encapsulating a single unit of behavior that you want to pass to other code. For
example, you would use a lambda expression if you want a certain action performed on each
element of a collection, when a process is completed, or when a process encounters an error.
• Use it if you need a simple instance of a functional interface and none of the preceding criteria apply
(for example, you do not need a constructor, a named type, fields, or additional methods).
Copyright: https://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html
Section Conclusion
Fact: Java 8 Features
In few samples it is simple to remember:
Java 8 new features.
2
Lambda Expressions, Method References, Functional Interfaces, Default Methods, Streams,
Optional Class, Nashorn JavaScript, New Date/Time API, Base64, New I/O
names.add(“Diana”);
names.add(“Mariah”);
names.add(“Dan”);
names.add(“Steve”);
names.add(“Mike”);
names.forEach(System.out::println);
}
}
Copyright: https://www.tutorialspoint.com/java8/index.htm
2.2 Java 8 Default Methods
Java 8 introduces a new concept of default method implementation in interfaces.
This capability is added for backward compatibility so that old interfaces can be used
to leverage the lambda expression capability of Java 8. For example, ‘List’ or
‘Collection’ interfaces do not have ‘forEach’ method declaration. Thus, adding such
method will simply break the collection framework implementations. Java 8
introduces default method so that List/Collection interface can have a default
implementation of forEach method, and the class implementing these interfaces
need not implement the same.
Copyright: https://www.tutorialspoint.com/java8/index.htm
2.2 Java 8 Default Methods
Copyright: https://www.tutorialspoint.com/java8/index.htm
2.2 Java 8 Default Methods
Copyright: https://www.tutorialspoint.com/java8/index.htm
2.3 Java 8 Lambda Expressions – Functional Programming
“Lambda expressions (λEs), also known as closures, provide a means to represent
anonymous methods. Supported by Project Lambda, λEs allow for the creation and use of
single method classes. These methods have a basic syntax that provides for the omission of
modifiers, the return type, and optional parameters. The specification for λEs is set out in
JSR 335, which is divided into seven parts: functional interfaces, lambda expressions,
method and constructor references, poly expressions, typing and evaluation, type inference,
and default methods.
“Modern IDEs have features to convert anonymous inner classes to lambda expressions.”
Programming paradigms
Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
2.3 Java 8 Lambda Expressions – Functional Programming
Functional Programming
What is a function?
• A side effect free computation that always result in same value when passed
with same argument.
Why should we embrace functional programming? (This does NOT mean to not
use OOP)
• Functional programs are simpler
• No side effects
• Fewer concurrency issues
Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
2.3 Java 8 Lambda Expressions – Functional Programming
Functional Languages
Lambda Expressions
Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
2.3 Java 8 Lambda Expressions
Java 8 Lambda Programming Style:
Lambda expressions typically include a parameter list, a return type,
and a body.
Syntax
A lambda expression is characterized by the following syntax −
@FunctionalInterface
interface GreetingService {
void sayMessage(String message);
}
}
Copyright: https://www.tutorialspoint.com/java8/index.htm
2.3 Java 8 Lambda and FI Sample
class LengthComparator implements Comparator<String> {
public int compare(String first, String second) {
return Integer.compare(first.length(), second.length());
}
}
What are first and second? They are both strings! Java is a strongly
typed language, and we must specify that as well:
Integer.compare(first.length(), second.length())
(String first, String second)
-> Integer.compare(first.length(), second.length())
The lambda expression from above is simply a block of code, together with the specification of any variables
that must be passed to the code.
Why the name? Many years ago, before there were any computers, the logician Alonzo Church wanted to
formalize what it means for a mathematical function to be effectively computable. (Curiously, there are
functions that are known to exist, but nobody knows how to compute their values.) He used the Greek letter
lambda (λ) to mark parameters. Had he known about the Java API, he would have written:
λfirst.λsecond.Integer.compare(first.length(), second.length())
Copyright: http://www.drdobbs.com/jvm/lambda-expressions-in-java-8/240166764
2.3 Java 8 Lambda and java.util.Comparator FI - Expressions Full Sample
tester.sortUsingJava7(names1);
System.out.println(names1);
System.out.println("Sort using Java 8 syntax: ");
tester.sortUsingJava8(names2);
System.out.println(names2);
}
Copyright: https://www.tutorialspoint.com/java8/index.htm
2.3 Java 8 Lambda and java.util.Comparator FI - Expressions Full Sample
Copyright: https://www.tutorialspoint.com/java8/index.htm
2.3 Java 8 Lambda and Functional Interface Sample
public class Java8TesterLambda {
public static void main(String args[]){
Java8Tester tester = new Java8Tester();
//with type declaration
MathOperation addition = (int a, int b) -> a + b;
//with out type declaration
MathOperation subtraction = (a, b) -> a - b;
//with return statement along with curly braces
MathOperation multiplication = (int a, int b) -> { return a * b; };
//without return statement and without curly braces
MathOperation division = (int a, int b) -> a / b;
//with parenthesis
GreetingService greetService1 = message -> System.out.println("Hello " + message);
//without parenthesis
GreetingService greetService2 = (message) -> System.out.println("Hello " + message);
interface MathOperation {
greetService1.sayMessage(”Jake"); int operation(int a, int b);
greetService2.sayMessage(”John"); }
}
... interface GreetingService {
void sayMessage(String message);
} }
//pass n as parameter
eval(list, n->true);
if(predicate.test(n)) {
System.out.println(n + " ");
}
}
}
}
Copyright: https://www.tutorialspoint.com/java8/index.htm
2.3 Java 8 Functional Interface & Lambda Sample
Copyright: http://bruceeckel.github.io/2015/10/17/are-java-8-lambdas-closures/
2.3 Java 8 Functional Interface & Lambda Sample
Type Inference
Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
2.4 Java 8 Processing Streams
Stream is a new abstract layer introduced in Java 8. Using
stream, you can process data in a declarative way similar to
SQL statements. For example, consider the following SQL
statement −
Stream Processing
Why?
Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
2.4 Java 8 Processing Streams
What is Stream?
Stream represents a sequence of objects from a source, which supports aggregate operations.
Following are the characteristics of a Stream :
• Aggregate operations − Stream supports aggregate operations like filter, map, limit, reduce,
find, match, and so on.
• Pipelining − Most of the stream operations return stream itself so that their result can be
pipelined. These operations are called intermediate operations and their function is to take input,
process them, and return output to the target. collect() method is a terminal operation which is
normally present at the end of the pipelining operation to mark the end of the stream.
• Automatic iterations − Stream operations do the iterations internally over the source
elements provided, in contrast to Collections where explicit iteration is required.
// Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
2.4 Java 8 Processing Streams API
Generating Streams
// Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
2.4 Java 8 Processing Streams
Understanding Java 8 Streams Code
// Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
2.4 Java 8 Processing Streams
Copyright: http://www.logicbig.com/tutorials/core-java-tutorial/java-util-stream/stream-cheat-sheet/
2.4 Java 8 Processing Streams
Copyright: http://www.logicbig.com/tutorials/core-java-tutorial/java-util-stream/stream-cheat-sheet/
2.4 Java 8 Processing Streams API
Copyright: http://www.logicbig.com/tutorials/core-java-tutorial/java-util-stream/stream-cheat-shee t/
2.4 Java 8 Processing Streams API
Copyright: https://www.tutorialspoint.com/java8/index.htm
2.4 Java 8 Processing Streams API
Filter – Intermediate Operations : Predicate
The ‘filter’ method (filtering) is used to eliminate elements based on a
criteria. The following code segment prints a count of empty strings using
filter.
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); //get # of empty string
int count = strings.stream().filter(string -> string.isEmpty()).count();
The ‘sorted’ method is used to sort the stream. The following code segment
shows how to print 10 random numbers in a sorted order.
Parallel Processing
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); //get # of empty string
int count = strings.parallelStream().filter(string -> string.isEmpty()).count();
Statistics
With Java 8, statistics collectors are introduced to calculate all statistics when
stream processing is being done.
// Copyright:http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html
2.4 Java 8 Processing Streams
// Copyright: http://www.oracle.com/technetwork/articles/java/architect-streams-pt2-2227132.html
2.4 Java 8 Processing Streams – Power of Collectors
Java 8 Streams Collectors
• Reduce a stream to a single value
• collect is a reduction operation
• They are used with collect terminal method
Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
2.4 Java 8 Processing Streams – Power of Collectors
Collectors class
Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
2.4 Java 8 Optional<T>
NullPointerException
Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
2.4 Java 8 Optional<T>
We end up writing …
Absence of value is not visible in the API • Null Object Pattern << Before Java 8
Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
• Optional << From Java 8
2.4 Java 8 Optional<T>
Optional
Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
2.4 Java 8 Optional<T>
8 boolean isPresent()Returns true if there is a value present,
otherwise false.
S. Method & Description
No.
9 <U>Optional<U> map(Function<? super T,? extends U>
1 static <T> Optional<T> empty()Returns an empty Optional instance. mapper)If a value is present, applies the provided mapping
function to it, and if the result is non-null, returns an
2 boolean equals(Object obj)Indicates whether some other object is Optional describing the result.
"equal to" this Optional.
10 static <T> Optional<T> of(T value)Returns an Optional
3 Optional<T> filter(Predicate<? super <T> predicate)If a value is with the specified present non-null value.
present and the value matches a given predicate, it returns an
Optional describing the value, otherwise returns an empty Optional. 11 static <T> Optional<T> ofNullable(T value)Returns an
Optional describing the specified value, if non-null,
4 <U> Optional<U> flatMap(Function<? super T,Optional<U>> otherwise returns an empty Optional.
mapper)If a value is present, it applies the provided Optional-bearing
mapping function to it, returns that result, otherwise returns an 12 T orElse(T other)Returns the value if present, otherwise
empty Optional. returns other.
5 T get()If a value is present in this Optional, returns the value, 13 T orElseGet(Supplier<? extends T> other)Returns the
otherwise throws NoSuchElementException. value if present, otherwise invokes other and returns the
result of that invocation.
6 int hashCode()Returns the hash code value of the present value, if
14 <X extends Throwable> T orElseThrow(Supplier<?
any, or 0 (zero) if no value is present.
extends X> exceptionSupplier)
Returns the contained value, if present, otherwise throws
7 void ifPresent(Consumer<? super T> consumer)If a value is present, an exception to be created by the provided supplier.
it invokes the specified consumer with the value, otherwise does
nothing.
Copyright: https://www.tutorialspoint.com/java8/java8_optional_class.htm
2.4 Java 8 Optional<T> Sample
Copyright: https://www.tutorialspoint.com/java8/java8_optional_class.htm
2.4 Java 8 Optional<T> Another Sample
Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
2.4 Java 8 New Date/Time API
What does the below program prints?
Sun Jan 12 00:00:00 IST 1913
Copyright: https://www.tutorialspoint.com/java8/java8_datetime_api.htm
2.4 Java 8 New Date/Time API
New API — Getting Started
§ Developed as part of JSR 310
§ Heavily inspired by Joda-Time library
§ New package — java.time
Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
2.4 Java 8 New Date/Time API
Temporal Adjuster
When you need to do advance date-time manipulation then you will use it.
Examples
• adjust to next Sunday
• adjust to first day of next month
• adjust to next working day
Copyright: https://github.com/shekhargulati/java8-the-missing-tutorial
2.4 Java 8 Base64
Base64 encoding is used in
practice usually for transport over
the network and heterogeneous
environments binary code such as
pictures or executable code. The
techniques is very simple: to
transform each 3 bytes values into
4 bytes value in order to avoid to
obtain values greater then 127 per
byte.
For instance, if the scope is to
encode the word “Man” into
Base64 encoding then it is
encoded as “TWFu”. Encoded in
ASCII (in ISO 8859-1, one value per
byte), M, a, n are stored as the
bytes 77 (0x4D), 97 (0x61), 110
(0x6E), which are 01001101,
01100001, 01101110 in base 2.
2.4 Java 8 Base64
With Java 8, Base64 has finally got its due. Java 8 now has inbuilt
encoder and decoder for Base64 encoding. In Java 8, we can use three
types of Base64 encoding −
Copyright: https://www.tutorialspoint.com/java8/java8_base64.htm
2.4 Java 8 Base64
1 static class Base64.Decoder This class implements a decoder for decoding byte
data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
2 static class Base64.Encoder This class implements an encoder for encoding byte
data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
Methods
S. No. Method Name & Description
1 static Base64.Decoder getDecoder()Returns a Base64.Decoder that decodes using
the Basic type base64 encoding scheme.
2 static Base64.Encoder getEncoder()Returns a Base64.Encoder that encodes using
the Basic type base64 encoding scheme.
Copyright: https://www.tutorialspoint.com/java8/java8_base64.htm
2.4 Java 8 Base64
Methods
S. No. Method Name & Description
3 static Base64.Decoder getMimeDecoder()Returns a Base64.Decoder that
decodes using the MIME type base64 decoding scheme.
4 static Base64.Encoder getMimeEncoder()
Returns a Base64.Encoder that encodes using the MIME type base64 encoding
scheme.
5 static Base64.Encoder getMimeEncoder(int lineLength, byte[]
lineSeparator)Returns a Base64.Encoder that encodes using the MIME type
base64 encoding scheme with specified line length and line separators.
6 static Base64.Decoder getUrlDecoder()Returns a Base64.Decoder that decodes
using the URL and Filename safe type base64 encoding scheme.
7 static Base64.Encoder getUrlEncoder()Returns a Base64.Encoder that encodes
using the URL and Filename safe type base64 encoding scheme.
Copyright: https://www.tutorialspoint.com/java8/java8_base64.htm
2.4 Java 8 Base64
Example without Base64 from Java 8
From the discussion here, and especially this answer, this is the function I currently
use (* Also, look into the javax.xml.bind.DatatypeConverter.parseBase64Binary() and
printHexBinary()):
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
“My own tiny benchmarks (a million bytes a thousand times, 256 bytes 10 million
times) showed it to be much faster than any other alternative, about half the time on
long arrays. Compared to the answer I took it from, switching to bitwise ops --- as
suggested in the discussion --- cut about 20% off of the time for long arrays. (Edit:
Performance is equivalent to Commons Codec, which uses very similar code.)”
Copyright: http://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java | http://stackoverflow.com/questions/41611248/java-convert-base64-to-hex-
string
2.4 Java 8 Base64
Copyright: https://www.tutorialspoint.com/java8/java8_base64.htm
Section Conclusions
But wait…
There’s More!
What’s
Thanks!Your Message?
Java SE Programming
End of Lecture 7 – summary of Java SE