SlideShare a Scribd company logo
1 of 25
LAMBDA IN JAVA 8
MIKE PONOMARENKO
ТЕОРИЯ

    Что такое замыкание (Lambda Expressions, JSR 335)
    Изменения в языке
    Сопутствующие изменения




2                         Sigma Ukraine
JSR 335
EARLY DRAFT R3
ТЕОРИЯ - ЗАМЫКАНИЯ

    Lambda expression
    – Анонимный метод
    – Может обращаться к переменным в локальной области
    – Нет лишнего .class при компиляции
    (x, y) => { System.out.println("The sum of x and y equals " +
    (x+y) )
    () => {return outerValue;}




4                             Sigma Ukraine
ПРИМЕР

error: local variables referenced from a lambda
expression must be final or effectively final

{
String ref = "a";
Runnable r = () -> {ref = "b";};
r.run();
System.out.println(ref);
}

 5                                  Sigma Ukraine
ПРИМЕР


{
Runnable r = ()->{System.out.println("hello");};
(new Thread(r)).start();
}




6                   Sigma Ukraine
ПРИМЕР


{
String ref = "a";
Runnable r = () -> {System.out.println(ref);};
r.run();
System.out.println(ref);
}



 7                 Sigma Ukraine
ПРИМЕР


String ref = "a";
Runnable r = new Runnable(){
      public void run(){
      System.out.println(ref);
    }
};
r.run();
System.out.println(ref);

 8                Sigma Ukraine
ПРИМЕР



{
List<String> strings = new LinkedList<String>();
Collections.sort(strings, (String a,String b) -> {
      return -(a.compareTo(b));
  });
}




 9                                Sigma Ukraine
ПРИМЕР



{
List<String> strings = new LinkedList<String>();
Collections.sort(strings, (a, b) -> -(a.compareTo(b)));
}




 10                               Sigma Ukraine
ТЕРИЯ, ИЗМЕНЕНИЯ В ЯЗЫКЕ

     Функциональный интерфейс
     – “A functional interface is an interface that has just one abstract
       method, and thus represents a single function contract. (In some
       cases, this "single" method may take the form of multiple
       abstract methods with override-equivalent signatures inherited
       from superinterfaces; in this case, the inherited methods logically
       represent a single method.)” - JSR
     Метод по умолчанию
     Ссылка на метод




11                               Sigma Ukraine
ТЕОРИЯ, МЕТОД ПО УМОЛЧАНИЮ



interface A{
       void doA();
}

interface B extends A{
      default void doB() {
            doA();
            doA();
       }
}
 12                     Sigma Ukraine
ТЕОРИЯ, МЕТОД ПО УМОЛЧАНИЮ



interface A{
       void doA();
      default void doB() {
             doA();
             doA();
       }
}




 13                    Sigma Ukraine
ТЕОРИЯ, ССЫЛКА НА МЕТОД

“A method reference is used to refer to a method without invoking it;
a constructor reference is similarly used to refer to a constructor without
 creating a new instance of the named class or array type.” - JSR


     System::getProperty
     "abc"::length
     String::length
     super::toString
     ArrayList::new
     int[]::new




14                                   Sigma Ukraine
ПРИМЕР


Collection<String> c = Arrays.asList("A","B","CD");
System.out.println(sum(c,String::length));




15                    Sigma Ukraine
ПРИМЕР

interface Code<T,R>{
         R exec(T input);
}

public static <T,R extends Number> long sum(Collection<T> c ,Code<T,R> cd){
         long rz = 0;
         for(T t : c){
                   R v = cd.exec(t);
                   if(v!=null) {
                            rz+=v.longValue();
                   }
         }
         return rz;
}



    16                           Sigma Ukraine
ПРИМЕР

import java.util.function.*;

public static <T,R extends Number> long sum(Collection<T> c ,
                                               Function<T,R> cd){
         long rz = 0;
         for(T t : c){
                   R v = cd.apply(t);
                   if(v!=null) {
                            rz+=v.longValue();
                   }
         }
         return rz;
}




  17                            Sigma Ukraine
JDK

     System.out.println(c.stream().map(String::length).sum());




18                            Sigma Ukraine
ТЕОРИЯ

  Добавляется в рантайм
  Множественное наследование поведения.
  Похоже на “C# extension methods”
  Наследование –
1. Суперкласс (“class wins”)
2. Более спецефичный интерфейс (“subtype wins”)
3. Делать вид что метод абстрактный
     1. Реализующий класс должен сделать выбор сам.
        A.super.m()




19                          Sigma Ukraine
JDK

interface Iterator<T> {
       boolean hasNext();
       T next();
       default void remove() {
               throw new UnsupportedOperationException();
       }
}




 20                       Sigma Ukraine
JDK

     interface Collection
     –   forEach
     –   removeIf(Predicate)
     –   stream()
     –   parallelStream()




21                             Sigma Ukraine
JDK


default Stream<E> stream() {
    return Streams.stream(() -> Streams.spliterator(iterator(),
              size(), Spliterator.SIZED), Spliterator.SIZED);
}

default Stream<E> parallelStream() {
    return stream().parallel();
}




  22                        Sigma Ukraine
JDK

public interface Stream<T> extends BaseStream<T, Stream<T>> {
  Stream<T> filter(Predicate<? super T> predicate);
  <R> Stream<R> map(Function<? super T, ? extends R> mapper);
  Stream<T> sorted();
  Optional<T> reduce(BinaryOperator<T> reducer);

         default Optional<T> max(Comparator<? super T> comparator) {
           return reduce(Comparators.greaterOf(comparator));
         }

         boolean anyMatch(Predicate<? super T> predicate);
}




    23                              Sigma Ukraine
JDK

     System.out.println(c.stream().map(String::length).sum());




24                            Sigma Ukraine
Thank you for your attention!

More Related Content

What's hot

CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
CodeFest
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
Mario Fusco
 
Java8 stream
Java8 streamJava8 stream
Java8 stream
koji lin
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
Pramod Kumar
 

What's hot (20)

Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Hierarchical free monads and software design in fp
Hierarchical free monads and software design in fpHierarchical free monads and software design in fp
Hierarchical free monads and software design in fp
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
The best language in the world
The best language in the worldThe best language in the world
The best language in the world
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
 
Java8 stream
Java8 streamJava8 stream
Java8 stream
 
Comparing JVM languages
Comparing JVM languagesComparing JVM languages
Comparing JVM languages
 
Kotlin, why?
Kotlin, why?Kotlin, why?
Kotlin, why?
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
 
The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202The Ring programming language version 1.8 book - Part 86 of 202
The Ring programming language version 1.8 book - Part 86 of 202
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
Implementation of 'go-like' language constructions in scala [english version]
Implementation of 'go-like' language constructions in scala [english version] Implementation of 'go-like' language constructions in scala [english version]
Implementation of 'go-like' language constructions in scala [english version]
 
Java patterns in Scala
Java patterns in ScalaJava patterns in Scala
Java patterns in Scala
 
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
 

Viewers also liked (7)

Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Lambda Expressions and Java 8 - Lambda Calculus, Lambda Expressions, Syntacti...
Lambda Expressions and Java 8 - Lambda Calculus, Lambda Expressions, Syntacti...Lambda Expressions and Java 8 - Lambda Calculus, Lambda Expressions, Syntacti...
Lambda Expressions and Java 8 - Lambda Calculus, Lambda Expressions, Syntacti...
 
Functions & closures
Functions & closuresFunctions & closures
Functions & closures
 
How To Use Higher Order Functions in Scala
How To Use Higher Order Functions in ScalaHow To Use Higher Order Functions in Scala
How To Use Higher Order Functions in Scala
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 

Similar to Lambda выражения и Java 8

Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)
Kaunas Java User Group
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and Analysis
Wiwat Ruengmee
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
Romain Francois
 
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpotВладимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Volha Banadyseva
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 

Similar to Lambda выражения и Java 8 (20)

New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)
 
Intro to Java 8 Lambdas
Intro to Java 8 LambdasIntro to Java 8 Lambdas
Intro to Java 8 Lambdas
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
What's new in java 8
What's new in java 8What's new in java 8
What's new in java 8
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and Analysis
 
Java 8
Java 8Java 8
Java 8
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Advanced Data Science with Apache Spark-(Reza Zadeh, Stanford)
Advanced Data Science with Apache Spark-(Reza Zadeh, Stanford)Advanced Data Science with Apache Spark-(Reza Zadeh, Stanford)
Advanced Data Science with Apache Spark-(Reza Zadeh, Stanford)
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Net practicals lab mannual
Net practicals lab mannualNet practicals lab mannual
Net practicals lab mannual
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda code
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpotВладимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 

More from Alex Tumanoff

Navigation map factory by Alexey Klimenko
Navigation map factory by Alexey KlimenkoNavigation map factory by Alexey Klimenko
Navigation map factory by Alexey Klimenko
Alex Tumanoff
 
Serialization and performance by Sergey Morenets
Serialization and performance by Sergey MorenetsSerialization and performance by Sergey Morenets
Serialization and performance by Sergey Morenets
Alex Tumanoff
 
Async clinic by by Sergey Teplyakov
Async clinic by by Sergey TeplyakovAsync clinic by by Sergey Teplyakov
Async clinic by by Sergey Teplyakov
Alex Tumanoff
 
Deep Dive C# by Sergey Teplyakov
Deep Dive  C# by Sergey TeplyakovDeep Dive  C# by Sergey Teplyakov
Deep Dive C# by Sergey Teplyakov
Alex Tumanoff
 
Bdd by Dmitri Aizenberg
Bdd by Dmitri AizenbergBdd by Dmitri Aizenberg
Bdd by Dmitri Aizenberg
Alex Tumanoff
 
Разработка расширений Firefox
Разработка расширений FirefoxРазработка расширений Firefox
Разработка расширений Firefox
Alex Tumanoff
 

More from Alex Tumanoff (20)

Sql server 2019 New Features by Yevhen Nedaskivskyi
Sql server 2019 New Features by Yevhen NedaskivskyiSql server 2019 New Features by Yevhen Nedaskivskyi
Sql server 2019 New Features by Yevhen Nedaskivskyi
 
Odessa .net-user-group-sql-server-2019-hidden-gems by Denis Reznik
Odessa .net-user-group-sql-server-2019-hidden-gems by Denis ReznikOdessa .net-user-group-sql-server-2019-hidden-gems by Denis Reznik
Odessa .net-user-group-sql-server-2019-hidden-gems by Denis Reznik
 
Azure data bricks by Eugene Polonichko
Azure data bricks by Eugene PolonichkoAzure data bricks by Eugene Polonichko
Azure data bricks by Eugene Polonichko
 
Sdlc by Anatoliy Anthony Cox
Sdlc by  Anatoliy Anthony CoxSdlc by  Anatoliy Anthony Cox
Sdlc by Anatoliy Anthony Cox
 
Kostenko ux november-2014_1
Kostenko ux november-2014_1Kostenko ux november-2014_1
Kostenko ux november-2014_1
 
Java 8 in action.jinq.v.1.3
Java 8 in action.jinq.v.1.3Java 8 in action.jinq.v.1.3
Java 8 in action.jinq.v.1.3
 
"Drools: декларативная бизнес-логика в Java-приложениях" by Дмитрий Контрерас...
"Drools: декларативная бизнес-логика в Java-приложениях" by Дмитрий Контрерас..."Drools: декларативная бизнес-логика в Java-приложениях" by Дмитрий Контрерас...
"Drools: декларативная бизнес-логика в Java-приложениях" by Дмитрий Контрерас...
 
Spring.new hope.1.3
Spring.new hope.1.3Spring.new hope.1.3
Spring.new hope.1.3
 
Sql saturday azure storage by Anton Vidishchev
Sql saturday azure storage by Anton VidishchevSql saturday azure storage by Anton Vidishchev
Sql saturday azure storage by Anton Vidishchev
 
Navigation map factory by Alexey Klimenko
Navigation map factory by Alexey KlimenkoNavigation map factory by Alexey Klimenko
Navigation map factory by Alexey Klimenko
 
Serialization and performance by Sergey Morenets
Serialization and performance by Sergey MorenetsSerialization and performance by Sergey Morenets
Serialization and performance by Sergey Morenets
 
Игры для мобильных платформ by Алексей Рыбаков
Игры для мобильных платформ by Алексей РыбаковИгры для мобильных платформ by Алексей Рыбаков
Игры для мобильных платформ by Алексей Рыбаков
 
Android sync adapter
Android sync adapterAndroid sync adapter
Android sync adapter
 
Async clinic by by Sergey Teplyakov
Async clinic by by Sergey TeplyakovAsync clinic by by Sergey Teplyakov
Async clinic by by Sergey Teplyakov
 
Deep Dive C# by Sergey Teplyakov
Deep Dive  C# by Sergey TeplyakovDeep Dive  C# by Sergey Teplyakov
Deep Dive C# by Sergey Teplyakov
 
Bdd by Dmitri Aizenberg
Bdd by Dmitri AizenbergBdd by Dmitri Aizenberg
Bdd by Dmitri Aizenberg
 
Неформальные размышления о сертификации в IT
Неформальные размышления о сертификации в ITНеформальные размышления о сертификации в IT
Неформальные размышления о сертификации в IT
 
Разработка расширений Firefox
Разработка расширений FirefoxРазработка расширений Firefox
Разработка расширений Firefox
 
"AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So...
"AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So..."AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So...
"AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So...
 
Patterns of parallel programming
Patterns of parallel programmingPatterns of parallel programming
Patterns of parallel programming
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

Lambda выражения и Java 8

  • 1. LAMBDA IN JAVA 8 MIKE PONOMARENKO
  • 2. ТЕОРИЯ Что такое замыкание (Lambda Expressions, JSR 335) Изменения в языке Сопутствующие изменения 2 Sigma Ukraine
  • 4. ТЕОРИЯ - ЗАМЫКАНИЯ Lambda expression – Анонимный метод – Может обращаться к переменным в локальной области – Нет лишнего .class при компиляции (x, y) => { System.out.println("The sum of x and y equals " + (x+y) ) () => {return outerValue;} 4 Sigma Ukraine
  • 5. ПРИМЕР error: local variables referenced from a lambda expression must be final or effectively final { String ref = "a"; Runnable r = () -> {ref = "b";}; r.run(); System.out.println(ref); } 5 Sigma Ukraine
  • 6. ПРИМЕР { Runnable r = ()->{System.out.println("hello");}; (new Thread(r)).start(); } 6 Sigma Ukraine
  • 7. ПРИМЕР { String ref = "a"; Runnable r = () -> {System.out.println(ref);}; r.run(); System.out.println(ref); } 7 Sigma Ukraine
  • 8. ПРИМЕР String ref = "a"; Runnable r = new Runnable(){ public void run(){ System.out.println(ref); } }; r.run(); System.out.println(ref); 8 Sigma Ukraine
  • 9. ПРИМЕР { List<String> strings = new LinkedList<String>(); Collections.sort(strings, (String a,String b) -> { return -(a.compareTo(b)); }); } 9 Sigma Ukraine
  • 10. ПРИМЕР { List<String> strings = new LinkedList<String>(); Collections.sort(strings, (a, b) -> -(a.compareTo(b))); } 10 Sigma Ukraine
  • 11. ТЕРИЯ, ИЗМЕНЕНИЯ В ЯЗЫКЕ Функциональный интерфейс – “A functional interface is an interface that has just one abstract method, and thus represents a single function contract. (In some cases, this "single" method may take the form of multiple abstract methods with override-equivalent signatures inherited from superinterfaces; in this case, the inherited methods logically represent a single method.)” - JSR Метод по умолчанию Ссылка на метод 11 Sigma Ukraine
  • 12. ТЕОРИЯ, МЕТОД ПО УМОЛЧАНИЮ interface A{ void doA(); } interface B extends A{ default void doB() { doA(); doA(); } } 12 Sigma Ukraine
  • 13. ТЕОРИЯ, МЕТОД ПО УМОЛЧАНИЮ interface A{ void doA(); default void doB() { doA(); doA(); } } 13 Sigma Ukraine
  • 14. ТЕОРИЯ, ССЫЛКА НА МЕТОД “A method reference is used to refer to a method without invoking it; a constructor reference is similarly used to refer to a constructor without creating a new instance of the named class or array type.” - JSR System::getProperty "abc"::length String::length super::toString ArrayList::new int[]::new 14 Sigma Ukraine
  • 15. ПРИМЕР Collection<String> c = Arrays.asList("A","B","CD"); System.out.println(sum(c,String::length)); 15 Sigma Ukraine
  • 16. ПРИМЕР interface Code<T,R>{ R exec(T input); } public static <T,R extends Number> long sum(Collection<T> c ,Code<T,R> cd){ long rz = 0; for(T t : c){ R v = cd.exec(t); if(v!=null) { rz+=v.longValue(); } } return rz; } 16 Sigma Ukraine
  • 17. ПРИМЕР import java.util.function.*; public static <T,R extends Number> long sum(Collection<T> c , Function<T,R> cd){ long rz = 0; for(T t : c){ R v = cd.apply(t); if(v!=null) { rz+=v.longValue(); } } return rz; } 17 Sigma Ukraine
  • 18. JDK System.out.println(c.stream().map(String::length).sum()); 18 Sigma Ukraine
  • 19. ТЕОРИЯ Добавляется в рантайм Множественное наследование поведения. Похоже на “C# extension methods” Наследование – 1. Суперкласс (“class wins”) 2. Более спецефичный интерфейс (“subtype wins”) 3. Делать вид что метод абстрактный 1. Реализующий класс должен сделать выбор сам. A.super.m() 19 Sigma Ukraine
  • 20. JDK interface Iterator<T> { boolean hasNext(); T next(); default void remove() { throw new UnsupportedOperationException(); } } 20 Sigma Ukraine
  • 21. JDK interface Collection – forEach – removeIf(Predicate) – stream() – parallelStream() 21 Sigma Ukraine
  • 22. JDK default Stream<E> stream() { return Streams.stream(() -> Streams.spliterator(iterator(), size(), Spliterator.SIZED), Spliterator.SIZED); } default Stream<E> parallelStream() { return stream().parallel(); } 22 Sigma Ukraine
  • 23. JDK public interface Stream<T> extends BaseStream<T, Stream<T>> { Stream<T> filter(Predicate<? super T> predicate); <R> Stream<R> map(Function<? super T, ? extends R> mapper); Stream<T> sorted(); Optional<T> reduce(BinaryOperator<T> reducer); default Optional<T> max(Comparator<? super T> comparator) { return reduce(Comparators.greaterOf(comparator)); } boolean anyMatch(Predicate<? super T> predicate); } 23 Sigma Ukraine
  • 24. JDK System.out.println(c.stream().map(String::length).sum()); 24 Sigma Ukraine
  • 25. Thank you for your attention!

Editor's Notes

  1. Hello and welcome to Sigma Ukraine!
  2. А нужен ли Б?
  3. Старый код работает, новый на старых классах тоже