SlideShare a Scribd company logo
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 (20)

Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
Andrzej Grzesik
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
langer4711
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
Jim Bethancourt
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
Yuriy Bondaruk
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
Rohit Verma
 
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
Jörn Guy Süß JGS
 
Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)
Trisha Gee
 
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
Ganesh Samarthyam
 
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)
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
Andrea Iacono
 
Java8lambda
Java8lambda Java8lambda
Java8lambda
Isuru Samaraweera
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
NewCircle Training
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
Buddhini Seneviratne
 
Java8
Java8Java8
Java8
Sunil Kumar
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
 
Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8
Isuru Samaraweera
 
Java8.part2
Java8.part2Java8.part2
Java8.part2
Ivan Ivanov
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
daewon jeong
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
langer4711
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
Yuriy Bondaruk
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
Rohit Verma
 
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
Jörn Guy Süß JGS
 
Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)
Trisha Gee
 
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
Ganesh Samarthyam
 
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)
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
Andrea Iacono
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
NewCircle Training
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
 
Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8
Isuru Samaraweera
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
daewon jeong
 

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
GlobalLogic Ukraine
 
Take a Look at Akka-Java
Take a Look at Akka-JavaTake a Look at Akka-Java
Take a Look at Akka-Java
GlobalLogic Ukraine
 
Spring vs EJB
Spring vs EJBSpring vs EJB
Spring vs EJB
GlobalLogic Ukraine
 
Java Performance Boost
Java Performance BoostJava Performance Boost
Java Performance Boost
GlobalLogic Ukraine
 
Object-Relational Mapping for Dummies
Object-Relational Mapping for DummiesObject-Relational Mapping for Dummies
Object-Relational Mapping for Dummies
GlobalLogic Ukraine
 
Nicety of Java 8 Multithreading
Nicety of Java 8 MultithreadingNicety of Java 8 Multithreading
Nicety of Java 8 Multithreading
GlobalLogic Ukraine
 
Commercial Development from the Inside
Commercial Development from the InsideCommercial Development from the Inside
Commercial Development from the Inside
GlobalLogic Ukraine
 
Антон Зотов - "Від інженера до AVP. Мій досвід побудови кар’єри в ІТ" Kharkiv...
Антон Зотов - "Від інженера до AVP. Мій досвід побудови кар’єри в ІТ" Kharkiv...Антон Зотов - "Від інженера до AVP. Мій досвід побудови кар’єри в ІТ" Kharkiv...
Антон Зотов - "Від інженера до AVP. Мій досвід побудови кар’єри в ІТ" Kharkiv...
Lviv Startup Club
 
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
GlobalLogic Ukraine
 
Object-Relational Mapping for Dummies
Object-Relational Mapping for DummiesObject-Relational Mapping for Dummies
Object-Relational Mapping for Dummies
GlobalLogic Ukraine
 
Commercial Development from the Inside
Commercial Development from the InsideCommercial Development from the Inside
Commercial Development from the Inside
GlobalLogic Ukraine
 
Антон Зотов - "Від інженера до AVP. Мій досвід побудови кар’єри в ІТ" Kharkiv...
Антон Зотов - "Від інженера до AVP. Мій досвід побудови кар’єри в ІТ" Kharkiv...Антон Зотов - "Від інженера до AVP. Мій досвід побудови кар’єри в ІТ" Kharkiv...
Антон Зотов - "Від інженера до AVP. Мій досвід побудови кар’єри в ІТ" Kharkiv...
Lviv Startup Club
 
Ad

Similar to Java 8 Intro - Core Features (20)

java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
BruceLee275640
 
Intro to java 8
Intro to java 8Intro to java 8
Intro to java 8
John Godoi
 
java8
java8java8
java8
Arik Abulafya
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
Indrajit Das
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern Java
Sina Madani
 
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 Interview Questions and Answers PDF By ScholarHat.pdfJava 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Scholarhat
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
Aniket Thakur
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
Jim Bethancourt
 
Java 8
Java 8Java 8
Java 8
vpulec
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
Ganesh Samarthyam
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
Leninkumar Koppoju
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
Knoldus Inc.
 
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
 
Java 8
Java 8Java 8
Java 8
Sudipta K Paik
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
Mark Harrison
 
A-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
A-Brief-Introduction-To-JAVA8_By_Srimanta_SahuA-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
A-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
Srimanta Sahu
 
14274730 (1).ppt
14274730 (1).ppt14274730 (1).ppt
14274730 (1).ppt
aptechaligarh
 
Insight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FPInsight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FP
Syed Awais Mazhar Bukhari
 
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
New York City College of Technology Computer Systems Technology Colloquium
 
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
Raffi Khatchadourian
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
BruceLee275640
 
Intro to java 8
Intro to java 8Intro to java 8
Intro to java 8
John Godoi
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
Indrajit Das
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern Java
Sina Madani
 
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 Interview Questions and Answers PDF By ScholarHat.pdfJava 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Scholarhat
 
Java 8
Java 8Java 8
Java 8
vpulec
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
Knoldus Inc.
 
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
 
A-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
A-Brief-Introduction-To-JAVA8_By_Srimanta_SahuA-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
A-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
Srimanta Sahu
 
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
Raffi Khatchadourian
 
Ad

More from GlobalLogic Ukraine (20)

GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic Ukraine
 
Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)
Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)
Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Ukraine
 
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 Ukraine
 
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 Ukraine
 
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”
GlobalLogic Ukraine
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxШтучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptx
GlobalLogic Ukraine
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxЗадачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptx
GlobalLogic Ukraine
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxЩо треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
GlobalLogic Ukraine
 
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...
GlobalLogic Ukraine
 
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 Ukraine
 
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...
GlobalLogic Ukraine
 
Страх і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationСтрах і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic Education
GlobalLogic Ukraine
 
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 Ukraine
 
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”
GlobalLogic Ukraine
 
“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 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
 
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 Ukraine
 
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”
GlobalLogic Ukraine
 
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 Ukraine
 
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic Ukraine
 
Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)
Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)
Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Ukraine
 
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 Ukraine
 
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 Ukraine
 
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”
GlobalLogic Ukraine
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxШтучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptx
GlobalLogic Ukraine
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxЗадачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptx
GlobalLogic Ukraine
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxЩо треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
GlobalLogic Ukraine
 
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...
GlobalLogic Ukraine
 
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 Ukraine
 
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...
GlobalLogic Ukraine
 
Страх і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationСтрах і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic Education
GlobalLogic Ukraine
 
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 Ukraine
 
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”
GlobalLogic Ukraine
 
“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 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
 
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 Ukraine
 
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”
GlobalLogic Ukraine
 
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 Ukraine
 

Recently uploaded (20)

Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 

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"