SlideShare a Scribd company logo
1 of 17
Java 8 intro : Core features
Spring 2016 Arkadii Tetelman
2
Java 8 New Features (Core and Collections)
• Interface’s Default (default methods)
• Functional Interfaces
• Lambdas
• Method References
• Streams (Stream API)
• Optional
3
Interface’s Default (default methods)
Java 8 extends interface declarations with two new items:
• default (default method implementation)
• static methods
• functional interface
4
Default Method
Default methods adds default method implementation that would be used
in the case when the implementer class won’t implement this method .
default is a new keyword in Java8 syntax
When you extend an interface that contains a default method, you can do
the following:
• Not mention the default method at all, which lets your extended interface
inherit the default method.
• Re-declare the default method, which makes it abstract.
• Redefine the default method, which overrides it.
5
Default Method code example
public interface DefaultExample {
default String defaultMethod() {
return "Default implementation";
}
}
private class DefaultableImpl implements DefaultExample {
}
protected abstract class DefaultableAbstractImpl implements DefaultExample {
public abstract String defaultMethod();
}
class OverrideImpl implements DefaultExample {
@Override
public String defaultMethod() {
return "Overridden implementation";
}
}
6
Static Methods in interfaces with example
Another greate feature delivered by Java 8 is that interfaces can declare (and
provide implementation) of static methods. Here is an example:
public interface TimeClient {
static public ZoneId getZoneId (String zoneString) {
try {
return ZoneId.of(zoneString);
} catch (DateTimeException e) {
return ZoneId.systemDefault();
}
}
default public ZonedDateTime getZonedDateTime(String zoneString) {
return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
}
LocalDateTime getLocalDateTime(); // Should be implemented!!!!!!!
}
7
Functional Interfaces
In Java 8 a functional interface is defined as an interface with exactly one abstract method.
New annotation @FunctionalInterface
//Invalid
@FunctionalInterface
public interface SomeInterfaceWithZeroAbstractMethods {}
//Invalid
@FunctionalInterface
public interface SomeInterfaceWithTWOAbstractMethods {
void firstAbstractMethodMethod();
int second(int k);
}
@FunctionalInterface
public interface SomeInterfaceWithONEAbstractMethods {
void f(); // abstract
static int g(int k) {return 0;} // static
default void h() {} // default
}
8
Built-in functional interfaces @ Java 8
Function Method Example
Supplier<T> T get() Supplier<String> stringSupplier = String::new;
String newInteger = stringSupplier.get(); // creates new String
Consumer<T> void accept(T t) List<String> one = Arrays.asList("A","AB","ABA","ABBA");
Consumer<String> style = (String s) ->
System.out.println("Item:"+s);
one.forEach(style);
Predicate<T> boolean test(T t); Predicate<Double> isNegative = x -> x < 0;
System.out.println(isNegative.test(new Double(1)));
Function<T,R> R apply(T t); Function<String, Integer> toInteger = Integer::valueOf;
Integer test = toInteger.apply("2016");
9
Lamdas (Lambda expressions)
A lambda expression (lambda) is a short-form replacement for an anonymous
class. Lambdas simplify the use of interfaces that declare single abstract methods,
that known as functional interfaces.
Core points:
• A lambda expression is a block of code with optional parameters
• Lambda expression is the best choice whenever you want a block of code
executed at a later point in time
• Lambda expression reduces amount of code
• Lambda expression used everywhere in Java8 (StreamAPI, Optionals, etc)
10
Lambda expressions syntax
Lambda Description
() -> 4; takes no value and returns 4;
x -> 3 * x; takes a number and returns the result of
tripling it
(x, y) -> x – y; takes two numbers and returns their
difference
(int x, int y) -> x + y; takes two integers and returns their sum
(String s) -> {
System.out.print("YES"+s);
System.err.print("YES"+s); }
takes a string and prints it to console and
err output with “YES” suffix
New keyword -> (minus with bigger, AKA structure dereference in C++)
(parameters) ->expression
or
(parameters) ->{ statements;}
Lambda Expression and Statements examples:
11
Method References
List<String> one = Arrays.asList("A","AB","ABA","ABBA");
//Reference to a static method
Collections.sort(one, Comparator.comparing((Function<String, Integer>) (s) ->
s.length()));
Collections.sort(one, Comparator.comparing(String::length));
List<String> two = Arrays.asList("1","2","3","4");
//Reference to an instance method of a particular object
two.forEach(System.out::println);
two.forEach((x) -> System.out.println(x));
//Reference to an instance method of an arbitrary object of a particular type
two.forEach(String::toString);
two.forEach((s) -> s.toString());
//Reference to a constructor
List<Integer> integers = two.stream().map(Integer::new).collect(Collectors.toList());
integers = two.stream().map((s) -> new Integer(s)).collect(Collectors.toList());
12
Streams (Stream API)
A newly added Stream API (java.util.stream) introduces real-world
functional-style programming into the Java.
A stream represents a sequence of elements and supports different kind
of operations to perform computations upon those elements.
Stream operations are
• intermediate
• terminal
Intermediate operations return a stream so we can chain multiple
intermediate operations without using semicolons.
Terminal operations are either void or return a non-stream result. In the
above example filter, map and sorted are intermediate operations whereas
forEach is a terminal operation.
For a full list of all available stream operations see the Stream Javadoc.
13
• Streams in Collection with some examples
Streams can be created from various data sources ,especially collections
Kind of Streams:
• stream() – process elements one by one in single thread
• parallelStream() – process elements in several threads
Operation Code Example
Filter
(Intermediate)
stringCollection.stream().filter((s) -> s.startsWith(“A"))
Sorted
(Intermediate)
stringCollection.parallelStream().sorted((a, b) -> b.compareTo(a));
Map
(Intermediate)
stringCollection.stream().map(String::toUpperCase);
Match
(Terminal)
stringCollection.stream().anyMatch((s) -> s.startsWith("a"))
stringCollection.stream().noneMatch((s) -> s.startsWith("z"))
Count
(Terminal)
stringCollection.stream().filter((s) -> s.startsWith(“B")).count();
14
• Streams in Collection with some examples #2
Operation Code Example
Collect
(Terminal)
stringCollection.stream().map(String::toUpperCase).
.collect(Collectors.toList());
Reduce
(Terminal)
List<Integer> list= Arrays.asList(1,2,3,4);
System.out.println(list.stream().reduce(0,Integer::sum));
Distinct
(Intermediate)
List<Integer> list= Arrays.asList(1,2,3,4,5,4,5);
System.out.println(list.stream().distinct().reduce(0,Integer::sum));
Peek
(Intermediate)
List<String> list= Arrays.asList(“1”,”2”,”3”,”4”,”5”);
list.stream().map(String::toUpperCase).peek((e)->System.out.print(e)).
collect(Collectors.toList())
Skip
(Intermediate)
List<String> list= Arrays.asList(“1”,”2”,”3”,”4”,”5”);
list.stream().map(String::toUpperCase).skip(2).
collect(Collectors.toList())
15
Optional vs NullPointerException
The … NullPointerException is by far the most popular cause of Java
application failures.
Long time ago the great Google Guava project introduced the Optional as
a solution to NullPointerException, discouraging codebase pollution with
null checks and encouraging developers to write cleaner code.
Inspired by Google Guava, the Optional is now a part of Java 8 library
Here is basic example
Optional<String> optional = Optional.of("Some value");
optional.isPresent(); // true
optional.get(); // "Some value"
optional.orElse("fallback"); // "Some value"
optional.ifPresent((s) -> System.out.println(s.charAt(2))); // “m"
16
Questions?
Email:
arkadii_tetelman@globallogic.com
Java 8 Intro - Core Features

More Related Content

What's hot

What's hot (20)

Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
 
Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
 
Java8lambda
Java8lambda Java8lambda
Java8lambda
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
Java8
Java8Java8
Java8
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8
 
Java8.part2
Java8.part2Java8.part2
Java8.part2
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 

Viewers also liked

Viewers also liked (8)

How to Learn a Programming Language in 25 Minutes
How to Learn a Programming Language in 25 MinutesHow to Learn a Programming Language in 25 Minutes
How to Learn a Programming Language in 25 Minutes
 
Take a Look at Akka-Java
Take a Look at Akka-JavaTake a Look at Akka-Java
Take a Look at Akka-Java
 
Spring vs EJB
Spring vs EJBSpring vs EJB
Spring vs EJB
 
Java Performance Boost
Java Performance BoostJava Performance Boost
Java Performance Boost
 
Object-Relational Mapping for Dummies
Object-Relational Mapping for DummiesObject-Relational Mapping for Dummies
Object-Relational Mapping for Dummies
 
Nicety of Java 8 Multithreading
Nicety of Java 8 MultithreadingNicety of Java 8 Multithreading
Nicety of Java 8 Multithreading
 
Commercial Development from the Inside
Commercial Development from the InsideCommercial Development from the Inside
Commercial Development from the Inside
 
Антон Зотов - "Від інженера до AVP. Мій досвід побудови кар’єри в ІТ" Kharkiv...
Антон Зотов - "Від інженера до AVP. Мій досвід побудови кар’єри в ІТ" Kharkiv...Антон Зотов - "Від інженера до AVP. Мій досвід побудови кар’єри в ІТ" Kharkiv...
Антон Зотов - "Від інженера до AVP. Мій досвід побудови кар’єри в ІТ" Kharkiv...
 

Similar to Java 8 Intro - Core Features

Similar to Java 8 Intro - Core Features (20)

Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
java8
java8java8
java8
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_final
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to Interfaces
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Java 8
Java 8Java 8
Java 8
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
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
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New features
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
 
Java 8
Java 8Java 8
Java 8
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 

More from GlobalLogic Ukraine

GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Ukraine
 

More from GlobalLogic Ukraine (20)

GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
 
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
 
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxШтучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptx
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxЗадачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptx
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxЩо треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
 
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
 
JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"
 
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
 
Страх і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationСтрах і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic Education
 
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
 
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
 
“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?
 
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
 
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
 
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
 
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
 
GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"
 
C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"
 
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 

Recently uploaded (20)

%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
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
 
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
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
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
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
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
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 

Java 8 Intro - Core Features

  • 1. Java 8 intro : Core features Spring 2016 Arkadii Tetelman
  • 2. 2 Java 8 New Features (Core and Collections) • Interface’s Default (default methods) • Functional Interfaces • Lambdas • Method References • Streams (Stream API) • Optional
  • 3. 3 Interface’s Default (default methods) Java 8 extends interface declarations with two new items: • default (default method implementation) • static methods • functional interface
  • 4. 4 Default Method Default methods adds default method implementation that would be used in the case when the implementer class won’t implement this method . default is a new keyword in Java8 syntax When you extend an interface that contains a default method, you can do the following: • Not mention the default method at all, which lets your extended interface inherit the default method. • Re-declare the default method, which makes it abstract. • Redefine the default method, which overrides it.
  • 5. 5 Default Method code example public interface DefaultExample { default String defaultMethod() { return "Default implementation"; } } private class DefaultableImpl implements DefaultExample { } protected abstract class DefaultableAbstractImpl implements DefaultExample { public abstract String defaultMethod(); } class OverrideImpl implements DefaultExample { @Override public String defaultMethod() { return "Overridden implementation"; } }
  • 6. 6 Static Methods in interfaces with example Another greate feature delivered by Java 8 is that interfaces can declare (and provide implementation) of static methods. Here is an example: public interface TimeClient { static public ZoneId getZoneId (String zoneString) { try { return ZoneId.of(zoneString); } catch (DateTimeException e) { return ZoneId.systemDefault(); } } default public ZonedDateTime getZonedDateTime(String zoneString) { return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString)); } LocalDateTime getLocalDateTime(); // Should be implemented!!!!!!! }
  • 7. 7 Functional Interfaces In Java 8 a functional interface is defined as an interface with exactly one abstract method. New annotation @FunctionalInterface //Invalid @FunctionalInterface public interface SomeInterfaceWithZeroAbstractMethods {} //Invalid @FunctionalInterface public interface SomeInterfaceWithTWOAbstractMethods { void firstAbstractMethodMethod(); int second(int k); } @FunctionalInterface public interface SomeInterfaceWithONEAbstractMethods { void f(); // abstract static int g(int k) {return 0;} // static default void h() {} // default }
  • 8. 8 Built-in functional interfaces @ Java 8 Function Method Example Supplier<T> T get() Supplier<String> stringSupplier = String::new; String newInteger = stringSupplier.get(); // creates new String Consumer<T> void accept(T t) List<String> one = Arrays.asList("A","AB","ABA","ABBA"); Consumer<String> style = (String s) -> System.out.println("Item:"+s); one.forEach(style); Predicate<T> boolean test(T t); Predicate<Double> isNegative = x -> x < 0; System.out.println(isNegative.test(new Double(1))); Function<T,R> R apply(T t); Function<String, Integer> toInteger = Integer::valueOf; Integer test = toInteger.apply("2016");
  • 9. 9 Lamdas (Lambda expressions) A lambda expression (lambda) is a short-form replacement for an anonymous class. Lambdas simplify the use of interfaces that declare single abstract methods, that known as functional interfaces. Core points: • A lambda expression is a block of code with optional parameters • Lambda expression is the best choice whenever you want a block of code executed at a later point in time • Lambda expression reduces amount of code • Lambda expression used everywhere in Java8 (StreamAPI, Optionals, etc)
  • 10. 10 Lambda expressions syntax Lambda Description () -> 4; takes no value and returns 4; x -> 3 * x; takes a number and returns the result of tripling it (x, y) -> x – y; takes two numbers and returns their difference (int x, int y) -> x + y; takes two integers and returns their sum (String s) -> { System.out.print("YES"+s); System.err.print("YES"+s); } takes a string and prints it to console and err output with “YES” suffix New keyword -> (minus with bigger, AKA structure dereference in C++) (parameters) ->expression or (parameters) ->{ statements;} Lambda Expression and Statements examples:
  • 11. 11 Method References List<String> one = Arrays.asList("A","AB","ABA","ABBA"); //Reference to a static method Collections.sort(one, Comparator.comparing((Function<String, Integer>) (s) -> s.length())); Collections.sort(one, Comparator.comparing(String::length)); List<String> two = Arrays.asList("1","2","3","4"); //Reference to an instance method of a particular object two.forEach(System.out::println); two.forEach((x) -> System.out.println(x)); //Reference to an instance method of an arbitrary object of a particular type two.forEach(String::toString); two.forEach((s) -> s.toString()); //Reference to a constructor List<Integer> integers = two.stream().map(Integer::new).collect(Collectors.toList()); integers = two.stream().map((s) -> new Integer(s)).collect(Collectors.toList());
  • 12. 12 Streams (Stream API) A newly added Stream API (java.util.stream) introduces real-world functional-style programming into the Java. A stream represents a sequence of elements and supports different kind of operations to perform computations upon those elements. Stream operations are • intermediate • terminal Intermediate operations return a stream so we can chain multiple intermediate operations without using semicolons. Terminal operations are either void or return a non-stream result. In the above example filter, map and sorted are intermediate operations whereas forEach is a terminal operation. For a full list of all available stream operations see the Stream Javadoc.
  • 13. 13 • Streams in Collection with some examples Streams can be created from various data sources ,especially collections Kind of Streams: • stream() – process elements one by one in single thread • parallelStream() – process elements in several threads Operation Code Example Filter (Intermediate) stringCollection.stream().filter((s) -> s.startsWith(“A")) Sorted (Intermediate) stringCollection.parallelStream().sorted((a, b) -> b.compareTo(a)); Map (Intermediate) stringCollection.stream().map(String::toUpperCase); Match (Terminal) stringCollection.stream().anyMatch((s) -> s.startsWith("a")) stringCollection.stream().noneMatch((s) -> s.startsWith("z")) Count (Terminal) stringCollection.stream().filter((s) -> s.startsWith(“B")).count();
  • 14. 14 • Streams in Collection with some examples #2 Operation Code Example Collect (Terminal) stringCollection.stream().map(String::toUpperCase). .collect(Collectors.toList()); Reduce (Terminal) List<Integer> list= Arrays.asList(1,2,3,4); System.out.println(list.stream().reduce(0,Integer::sum)); Distinct (Intermediate) List<Integer> list= Arrays.asList(1,2,3,4,5,4,5); System.out.println(list.stream().distinct().reduce(0,Integer::sum)); Peek (Intermediate) List<String> list= Arrays.asList(“1”,”2”,”3”,”4”,”5”); list.stream().map(String::toUpperCase).peek((e)->System.out.print(e)). collect(Collectors.toList()) Skip (Intermediate) List<String> list= Arrays.asList(“1”,”2”,”3”,”4”,”5”); list.stream().map(String::toUpperCase).skip(2). collect(Collectors.toList())
  • 15. 15 Optional vs NullPointerException The … NullPointerException is by far the most popular cause of Java application failures. Long time ago the great Google Guava project introduced the Optional as a solution to NullPointerException, discouraging codebase pollution with null checks and encouraging developers to write cleaner code. Inspired by Google Guava, the Optional is now a part of Java 8 library Here is basic example Optional<String> optional = Optional.of("Some value"); optional.isPresent(); // true optional.get(); // "Some value" optional.orElse("fallback"); // "Some value" optional.ifPresent((s) -> System.out.println(s.charAt(2))); // “m"