The slides of my JavaOne talk: Java 8 Stream API and RxJava Comparison: Patterns and Performances.
The spliterators patterns can be found here: https://github.com/JosePaumard/jdk8-spliterators.
The slides of my JavaOne 2016 talk. This talk is a tutorial on how to write lambda expressions, how to compose them using default methods in functional interfaces, and how to create factory methods in those interfaces. Many examples and patterns are provided.
The slides of my talk at Devoxx BE 2017. This in depth talk is all about collectors: those available, because we need to know them, those that we can create, those we had no idea they could be created, and the others, as there is in fact no limit to what can be done with this API. The concept of downstream collector will be used to show how we can write entire data processing pipelines using collectors only, and pass them as parameters to other pipelines.
The slides of my JavaOne 2016 talk. This talk is a tutorial on how to write lambda expressions, how to compose them using default methods in functional interfaces, and how to create factory methods in those interfaces. Many examples and patterns are provided.
The slides of my talk at Devoxx BE 2017. This in depth talk is all about collectors: those available, because we need to know them, those that we can create, those we had no idea they could be created, and the others, as there is in fact no limit to what can be done with this API. The concept of downstream collector will be used to show how we can write entire data processing pipelines using collectors only, and pass them as parameters to other pipelines.
The slides of my university talk at Devoxx BE 2015. Presentation of the Java 8 Stream API and RxJava, pattern and performance comparisons. Presentation of the upcoming reactive API in Java 9: the Flow API.
The spliterators patterns can be found here: https://github.com/JosePaumard/jdk8-spliterators.
The slides of my JavaOne 2017 talk. It describes how you can create API using functional interfaces, default and static methods starting with Java 8. You can watch the video here: https://www.youtube.com/watch?v=64UO1YjVcZ0
The slides of my university talk, Devoxx Belgium 2016.
The goal of this talk is to compare the two most popular implementations of List: LinkedList and ArrayList, and provide hints on which one to use in what case.
Those are the slides of the presentation we made with Maurice Naftalin à Goto: Copenhagen 2019.
Functional programmers have been saying for decades that they know the way to the future. Clearly they've been wrong, since imperative languages are still far more popular. Clearly they've also been right, as the advantages of functional programming have become increasingly obvious. Is it possible to combine the two models? Scala is one language that does this, and Java too has been on a journey, which still continues, of learning from functional languages and carefully adding features from them. In this talk, we'll review what Java has learned from functional languages, what it can still learn, and how its added features compare to Scala's original ones.
Lambdas and Streams Master Class Part 2José Paumard
These are the slides of the talk we made with Stuart Marks at Devoxx Belgium 2018. This second part covers the Stream API, reduction and the Collector API.
What is the state of lambda expressions in Java 11? Lambda expressions are the major feature of Java 8, having an impact on most of the API, including the Streams and Collections API. We are now living the Java 11 days; new features have been added and new patterns have emerged. This highly technical Deep Dive session will visit all these patterns, the well-known ones and the new ones, in an interactive hybrid of lecture and laboratory. We present a technique and show how it helps solve a problem. We then present another problem, and give you some time to solve it yourself. Finally, we present a solution, and open for questions, comments, and discussion. Bring your laptop set up with JDK 11 and your favorite IDE, and be prepared to think!
Slides from the talk we did with Maurice Naftalin for Devoxx Belgium 2019.
Functional programmers have been saying for decades that they know the way to the future.
Clearly they have been wrong, since imperative languages are still far more popular.
Clearly they have also been right, as the advantages of functional programming have become increasingly obvious. Is it possible to face both ways, and combine the two models?
Scala is one language that does this, and Java too has been on a journey, which still continues, of learning from functional languages and carefully adding features from them.
In this talk, we will review what Java has learned from functional languages, what it can still learn, and how its added features compare to Scala's original ones.
Lambda and Stream Master class - part 1José Paumard
These are the slides of the talk we made with Stuart Marks at Devoxx Belgium 2018. This first part covers Lambda Expressions and API design with functional interfaces.
What is the state of lambda expressions in Java 11? Lambda expressions are the major feature of Java 8, having an impact on most of the API, including the Streams and Collections API. We are now living the Java 11 days; new features have been added and new patterns have emerged. This highly technical Deep Dive session will visit all these patterns, the well-known ones and the new ones, in an interactive hybrid of lecture and laboratory. We present a technique and show how it helps solve a problem. We then present another problem, and give you some time to solve it yourself. Finally, we present a solution, and open for questions, comments, and discussion. Bring your laptop set up with JDK 11 and your favorite IDE, and be prepared to think!
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
Java 8 Stream API. A different way to process collections.David Gómez García
A look on one of the features of Java 8 hidden behind the lambdas. A different way to iterate Collections. You'll never see the Collecions the same way.
These are the slides I used on my talk at the "Tech Thursday" by Oracle in June in Madrid.
Asynchronous API in Java8, how to use CompletableFutureJosé Paumard
Slides of my talk as Devoxx 2015. How to set up asynchronous data processing pipelines using the CompletionStage / CompletableFuture API, including how to control threads and how to handle exceptions.
Slides of the talk we made with David Delabasee (@delabassee) at Devoxx 2015. A list of Java SE 8 patterns that you can use in Java EE 7 applications, thanks to the support of the major app servers.
Odessapy2013 - Graph databases and PythonMax Klymyshyn
Page 10 "Я из Одессы я просто бухаю." translation: I'm from Odessa I just drink. Meaning his drinking a lot of "Vodka" ^_^ (@tuc @hackernews)
This is local meme - when someone asking question and you will look stupid in case you don't have answer.
Functional programming is all the rage. It can undoubtedly produce cleaner and more expressive code, but why switch to Scala or wait for Java 8? In fact, there are many ways to dramatically improve your Java code quality by using a more functional style today. This presentation discusses how techniques such as functional programming, using fluent APIs, and other clean coding practices can make your code more concise, more readable, and much easier to maintain. But more importantly, you will learn about libraries such as LambdaJ and Google Guava that make this possible today with your existing Java code base.
Well-architected libraries for functional programming are at once immensely beautiful and practical. They are simple but extraordinarily powerful, helping users solve their problems by snapping together Lego-like building blocks, each of which has just one purpose. Yet, there is a surprising dearth of material on how developers can construct their own well-architected functional code. Many functional programming tutorials talk discuss type safety and making illegal states unrepresentable, but few speak on the subject of good functional interface design.
In this presentation, John A. De Goes takes to the stage to discuss a nebulous and underrated tool in the arsenal of every functional programmer. Called *orthogonality*, this tool allows programmers to craft the building blocks of their functional code at "right angles", so so they can be reasoned about simply and composed predictably to solve complex problems. John introduces the concept of orthogonality, looking at its geometric and algebraic origins, presents a way to measure orthogonality, and then walks through a number of interface examples, comparing non-orthogonal designs with orthogonal ones.
By the end of the session, attendees should have a newfound appreciation for how important orthogonality is to constructing good functional interfaces, and they should develop the early stages of an intuition about how to slice up a complex problem into core, single-purpose, composable building blocks.
Halogen is a popular choice for building front-end user-interfaces with PureScript. Often described as a purely functional version of React, Halogen allows building user-interfaces by composing declarative, self-contained components, including effectful components those built from third-party Javascript libraries.
In this presentation, John presents a high-level summary of where Halogen has come from, how it works right now, and what are the main drawbacks to both FRP and React. John then suggests that incremental computation should be the foundation for the next major version of Halogen, and sketches out a possible way of achieving that in a declarative fashion.
All Aboard The Scala-to-PureScript Express!John De Goes
Many Scala programmers have embraced functional programming, but the syntax and semantics of programming languages in the Haskell family remains a mystery. In this talk, Scala developers (and to some extent, Java developers) will see how the types, data structures, traits / interfaces, packages, and so forth translate into their PureScript counterparts.
The slides of my university talk at Devoxx BE 2015. Presentation of the Java 8 Stream API and RxJava, pattern and performance comparisons. Presentation of the upcoming reactive API in Java 9: the Flow API.
The spliterators patterns can be found here: https://github.com/JosePaumard/jdk8-spliterators.
The slides of my JavaOne 2017 talk. It describes how you can create API using functional interfaces, default and static methods starting with Java 8. You can watch the video here: https://www.youtube.com/watch?v=64UO1YjVcZ0
The slides of my university talk, Devoxx Belgium 2016.
The goal of this talk is to compare the two most popular implementations of List: LinkedList and ArrayList, and provide hints on which one to use in what case.
Those are the slides of the presentation we made with Maurice Naftalin à Goto: Copenhagen 2019.
Functional programmers have been saying for decades that they know the way to the future. Clearly they've been wrong, since imperative languages are still far more popular. Clearly they've also been right, as the advantages of functional programming have become increasingly obvious. Is it possible to combine the two models? Scala is one language that does this, and Java too has been on a journey, which still continues, of learning from functional languages and carefully adding features from them. In this talk, we'll review what Java has learned from functional languages, what it can still learn, and how its added features compare to Scala's original ones.
Lambdas and Streams Master Class Part 2José Paumard
These are the slides of the talk we made with Stuart Marks at Devoxx Belgium 2018. This second part covers the Stream API, reduction and the Collector API.
What is the state of lambda expressions in Java 11? Lambda expressions are the major feature of Java 8, having an impact on most of the API, including the Streams and Collections API. We are now living the Java 11 days; new features have been added and new patterns have emerged. This highly technical Deep Dive session will visit all these patterns, the well-known ones and the new ones, in an interactive hybrid of lecture and laboratory. We present a technique and show how it helps solve a problem. We then present another problem, and give you some time to solve it yourself. Finally, we present a solution, and open for questions, comments, and discussion. Bring your laptop set up with JDK 11 and your favorite IDE, and be prepared to think!
Slides from the talk we did with Maurice Naftalin for Devoxx Belgium 2019.
Functional programmers have been saying for decades that they know the way to the future.
Clearly they have been wrong, since imperative languages are still far more popular.
Clearly they have also been right, as the advantages of functional programming have become increasingly obvious. Is it possible to face both ways, and combine the two models?
Scala is one language that does this, and Java too has been on a journey, which still continues, of learning from functional languages and carefully adding features from them.
In this talk, we will review what Java has learned from functional languages, what it can still learn, and how its added features compare to Scala's original ones.
Lambda and Stream Master class - part 1José Paumard
These are the slides of the talk we made with Stuart Marks at Devoxx Belgium 2018. This first part covers Lambda Expressions and API design with functional interfaces.
What is the state of lambda expressions in Java 11? Lambda expressions are the major feature of Java 8, having an impact on most of the API, including the Streams and Collections API. We are now living the Java 11 days; new features have been added and new patterns have emerged. This highly technical Deep Dive session will visit all these patterns, the well-known ones and the new ones, in an interactive hybrid of lecture and laboratory. We present a technique and show how it helps solve a problem. We then present another problem, and give you some time to solve it yourself. Finally, we present a solution, and open for questions, comments, and discussion. Bring your laptop set up with JDK 11 and your favorite IDE, and be prepared to think!
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
Java 8 Stream API. A different way to process collections.David Gómez García
A look on one of the features of Java 8 hidden behind the lambdas. A different way to iterate Collections. You'll never see the Collecions the same way.
These are the slides I used on my talk at the "Tech Thursday" by Oracle in June in Madrid.
Asynchronous API in Java8, how to use CompletableFutureJosé Paumard
Slides of my talk as Devoxx 2015. How to set up asynchronous data processing pipelines using the CompletionStage / CompletableFuture API, including how to control threads and how to handle exceptions.
Slides of the talk we made with David Delabasee (@delabassee) at Devoxx 2015. A list of Java SE 8 patterns that you can use in Java EE 7 applications, thanks to the support of the major app servers.
Odessapy2013 - Graph databases and PythonMax Klymyshyn
Page 10 "Я из Одессы я просто бухаю." translation: I'm from Odessa I just drink. Meaning his drinking a lot of "Vodka" ^_^ (@tuc @hackernews)
This is local meme - when someone asking question and you will look stupid in case you don't have answer.
Functional programming is all the rage. It can undoubtedly produce cleaner and more expressive code, but why switch to Scala or wait for Java 8? In fact, there are many ways to dramatically improve your Java code quality by using a more functional style today. This presentation discusses how techniques such as functional programming, using fluent APIs, and other clean coding practices can make your code more concise, more readable, and much easier to maintain. But more importantly, you will learn about libraries such as LambdaJ and Google Guava that make this possible today with your existing Java code base.
Well-architected libraries for functional programming are at once immensely beautiful and practical. They are simple but extraordinarily powerful, helping users solve their problems by snapping together Lego-like building blocks, each of which has just one purpose. Yet, there is a surprising dearth of material on how developers can construct their own well-architected functional code. Many functional programming tutorials talk discuss type safety and making illegal states unrepresentable, but few speak on the subject of good functional interface design.
In this presentation, John A. De Goes takes to the stage to discuss a nebulous and underrated tool in the arsenal of every functional programmer. Called *orthogonality*, this tool allows programmers to craft the building blocks of their functional code at "right angles", so so they can be reasoned about simply and composed predictably to solve complex problems. John introduces the concept of orthogonality, looking at its geometric and algebraic origins, presents a way to measure orthogonality, and then walks through a number of interface examples, comparing non-orthogonal designs with orthogonal ones.
By the end of the session, attendees should have a newfound appreciation for how important orthogonality is to constructing good functional interfaces, and they should develop the early stages of an intuition about how to slice up a complex problem into core, single-purpose, composable building blocks.
Halogen is a popular choice for building front-end user-interfaces with PureScript. Often described as a purely functional version of React, Halogen allows building user-interfaces by composing declarative, self-contained components, including effectful components those built from third-party Javascript libraries.
In this presentation, John presents a high-level summary of where Halogen has come from, how it works right now, and what are the main drawbacks to both FRP and React. John then suggests that incremental computation should be the foundation for the next major version of Halogen, and sketches out a possible way of achieving that in a declarative fashion.
All Aboard The Scala-to-PureScript Express!John De Goes
Many Scala programmers have embraced functional programming, but the syntax and semantics of programming languages in the Haskell family remains a mystery. In this talk, Scala developers (and to some extent, Java developers) will see how the types, data structures, traits / interfaces, packages, and so forth translate into their PureScript counterparts.
Java 8 supports lambdas. It's API also comes with Streams support.
But Knowing some concepts on Functional Programming may help you get a lot more from what this new version of Java has to offer.
Database structure Structures Link list and trees and Recurison complete Adnan abid
Database structure Structures Link list and trees and Recurison complete Database structure Structures Link list and trees and Recurison complete Database structure Structures Link list and trees and Recurison complete Database structure Structures Link list and trees and Recurison complete Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete Database structure Structures Link list and trees and Recurison complete Database structure Structures Link list and trees and Recurison complete
Functional programming has started (re)gaining prominence in recent years, and with good reason too. Functional programs lend an elegant solution to the concurrency problem, result in more modular systems, are more concise and are easier to test. While modern languages like Scala and Clojure have embraced the functional style whole-heartedly, Java has lagged a bit behind in its treatment of functions as first-class citizens. With the advent of Java 8 and its support for lambdas, however, Java programmers can finally start reaping the power of functional programs as well. Even without Java 8, it is possible to adopt a functional style with the aid of excellent libraries such as Guava.
L'API la plus utilisée du JDK est sans aucun doute l'API Collection. Brillamment conçue il y a un peu plus de 15 ans, elle est encore aujourd'hui au coeur de toutes les applications Java. En 2004, elle a subi son premier lifting, avec l'introduction des génériques. Cette mise à jour, bien qu'importante, n'a cependant pas modifié ses patterns d'utilisation. Avec l'introduction des lambdas en Java 8, l'API Collection est à nouveau réécrite, mais cette fois la situation est différente : ses patterns d'utilisation sont complètement changés.
La première partie de cette conférence introduit les lambda expressions, comment les écrire, et ce qu'elle nous apportent en tant que développeurs. La deuxième partir présente en détail les nouveaux patterns introduits par les API Stream et Collector. Ces nouvelles API vont changer la façon dont nous allons pouvoir traiter les collections de grande taille, y compris en parallèle, avec un modèle de programmation très simple, et des patterns très puissants. Cette puissance sera montrée dans des exemples réels, qui monteront comment Java 8 va pouvoir nous aider à écrire simplement du code efficace et performant.
In this Meetup Victor Perepelitsky - R&D Technical Leader at LivePerson leading the 'Real Time Event Processing Platform' team , will talk about Java 8', 'Stream API', 'Lambda', and 'Method reference'.
Victor will clarify what functional programming is and how can you use java 8 in order to create better software.
Victor will also cover some pain points that Java 8 did not solve regarding functionality and see how you can work around it.
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautésAlphorm
Formation complète ici:
http://www.alphorm.com/tutoriel/formation-en-ligne-autodesk-revit-2018-les-nouveautes
Autodesk Revit fait sans doute partie des logiciels d’architecture 3D les plus performants actuellement. Il dispose d'une large gamme de fonctionnalités permettant de produire des images 3D de qualité.
Autodesk Revit est un puissant logiciel de traitement d'images 3D. Plus précisément, le programme permet de concevoir, de visualiser, et bien entendu de modifier des créations en architecture 3D. Il a été conçu pour être bien précis dans ses œuvres, de l'esquisse au crayon à la vitesse et la flexibilité de l'application.
Cette formation Revit 2018 vous permettra de maîtriser les nouveautés de Revit 2018, le logiciel d'architecture 3D, utilisé par de nombreux passionnés et professionnels.
Au cours de cette formation Revit 2018, vous aborderez les nouveautés concernant les améliorations de textes, la création des escaliers multi-étages, l’hébergement des garde-corps sur une topographie, la fonctionnalité de liaison d’un fichier Navisworks sur Revit, les améliorations concernant la création des garde-corps par esquisse.
Avec cette formation Revit 2018 les nouveautés, vous apprendrez à utiliser les nouveautés du logiciel de manière optimale afin de devenir un Spécialiste sur Revit 2018.
Formation complète ici:
http://www.alphorm.com/tutoriel/formation-en-ligne-java-server-faces
Nous rappelons tout d’abord les technologies JSP et Servlet, qui servent de base à JSF. Avec JSP et Servlet, nous créons des applications Web dynamiques. Puis, en nous appuyant sur les Servlets, nous abordons JSF. Ce qui caractérise les pages JSF, c’est l’absence totale de code Java et la présence de balises spécifiques, les facelets. Pour faire le lien entre les pages HTML et les composants Java, nous présentons Expression Language, qui permet d’écrire des expressions qui lisent ou écrivent les données.
Ensuite, nous détaillons certains composants essentiels à la construction des pages Web, et après ce chapitre, vous êtes capable de créer une interface riche et agréable à l’utilisateur. Ces composants ont ou pas un équivalent HTML. Ces composants graphiques sont ensuite accompagnés de convertisseurs, listeners et de validateurs qui permettront d’éviter de coder les règles élémentaires liées à la saisie et à la modification des données.
Nous n’oublions pas le code Java, car les beans managés ont leur chapitre, afin de préciser les règles à suivre pour qu’ils s’intègrent parfaitement dans l’application. Plusieurs choix s’offrent à nous, nous choisissons le plus pertinent.
Pour améliorer le rendu et la fluidité de l’interface, nous utiliserons Ajax, et nous montrerons comment il est simple d’introduire cette technologie dans les pages JSF. Avec Ajax, qui utilise donc du JavaScript, nous obtiendrons des mises à jour plus discrètes et plus rapides.
Enfin, nous finirons par décrire les détails de configuration concernant les beans, l’internationalisation, les flux et la sécurité. La configuration repose pour une bonne part sur l’écriture de fichiers XML, et par ailleurs beaucoup sur le respect de règles et de conventions. Le paramétrage sera abordé en prenant comme exemple GlassFish.
Alphorm.com Formation CND 2/2: Réussir la certificationAlphorm
Formation complète ici:
http://www.alphorm.com/tutoriel/formation-en-ligne-cnd-certified-network-defender-2-2-reussir-la-certification-cnd
Le Certified Network Defender (CND) est un cours vendor-neutral, c'est à dire sans orientation technique vis à vis d'un quelconque fournisseur de matériel ou d'éditeur de solutions de sécurité des réseaux informatiques
Le cursus CND est un cours 50 % pratique sous forme de labs, modélisant les activités courantes d'administrateurs réseaux, basés sur les outils et techniques les plus utilisés dans la sécurité réseau.
Ces éléments ont été mise en place grâce aux meilleurs pratiques établies par le ministère américain de la Défense (DoD) ainsi qu'au travers du framework de cybersécurité décrit par le National Initiative of Cybersecurity Education.
Le programme permet aux administrateurs réseaux de se préparer aux technologies de la sécurité des réseaux ainsi que sur les opérations et méthodologies qui y sont relatives et ainsi appliquer une logique de sécurité en profondeur (Defense-in-Depth)
Lors de Tome 2, nous allons pouvoir approfondir nos connaissances concernant le durcissement réseaux et systèmes, ainsi que la découverte de différentes technologies pour la protection et réseaux et systèmes informatiques.
Nous allons aussi pouvoir découvrir les différentes méthodologies et approches afin de pouvoir configurer, déployer et exploiter correctement différents périphériques de sécurité (HIDS, IDS, VPN, Firewall), la supervision des réseaux informatiques, la gestion des backups, ainsi que la découverte d’une nouvelle notion tout aussi importante et qui concerne la sécurité organisationnelle (Avec la gestion du risque et des incidents de sécurité informatique).
Formation complète ici:
http://www.alphorm.com/tutoriel/formation-en-ligne-java-8-les-nouveautes
La formation va concerner tous les horizons nouveaux de Java : nous commencerons par les nouveautés syntaxiques, comme les expressions lambdas, couplées ou non aux streams, qui ouvrent la porte à une nouvelle façon de programmer.
La formation va aussi dévoiler des nouveautés dans les APIs Java, dans les classes de collections, les classes de gestion de la concurrence et des réseaux.
La partie graphique avec JavaFX sera présentée, puisque cette API remplace Swing à compter de Java8.
Ensuite nous présenterons les nouvelles classes de gestion des dates et du temps.
Les nouveautés dans le domaine de la sécurité seront abordées, avec le support de nouveaux algorithmes.
Enfin, nous parlerons des outils nouveaux ou modifiés, y compris le moteur js.
Beholding the giant pyramid of application development; why Ajax applications...Javeline B.V.
Building large and complex web applications using the open browser stack without any plugins is taking off (google wave), and with the support of rapidly innovating browsers like Firefox and Chrome it looks like it is bypassing proprietary platforms. This talk illustrates why the web browser and HTML5 are positioned to become the global platform for applications and how Ajax technologies like our ajax.org are optimizing application development.
A subject named "Internet Technology and its Applications" subject's introduction taught as part of B.E.IV (Computer), 8th semester students, VNSGU, Surat, Gujarat State, India.
Slajdy z konferencji Confitura 2019.
Wszyscy znamy podejście REST do definiowania API naszych aplikacji. Jednak REST ma swoje wady i ograniczenia. To dla tego Facebook stworzył GraphQL jako alternatywę. W mojej prezentacji przedstawię ograniczenia RESTa i jak je rozwiązuje GraphQL. Pokażę składnię, zalety jak i wady. Będzie też jak zaimplementować GraphQL w Javie oraz co jeszcze warto o nim wiedzieć.
On-Ramp to Graph Databases and Amazon Neptune (DAT335) - AWS re:Invent 2018Amazon Web Services
How do you get started with a graph database? Learn how to quickly and easily spin up a graph database and get started writing traversals over your connected data.
The Power of RxJS in Nativescript + AngularTracy Lee
Learn the basics of use and power of RxJS in NativeScript & Angular in this presentation given at NativeScript Developer Days in New York City September 2017
Similar to Java 8 Stream API and RxJava Comparison (20)
The Loom project has been under work for many years, and just delivered Virtual Threads as a preview feature in the JDK 19. We now have a very precise idea of what they are and what you can do with them. Our good old Threads, created more than 25 years ago, will see a new kind of lightweight threads. This presentation shows you that creating a thread is easier and much cheaper, allowing the creation of millions of them in a single JVM. These virtual threads can be block at almost no cost. These new virtual threads bring with them new notions that will be covered in this talk. Loom threads are coming, and they will change the landscape of concurrent programming in Java.
The features released between Java 11 and Java 17 have brought a greater opportunity for developers to improve application development productivity as well and code expressiveness and readability. In this deep-dive session, you will discover all the recent Project Amber features added to the Java language such as Text blocks, Records (including Records serialization), Pattern Matching for instanceof, switch expression, sealed classes, and pattern matching for switch. The main goal of the Amber Project is to bring Pattern Matching to the Java platform, which will impact both the language and the JDK APIs. You will discover record patterns, array patterns, as well as deconstruction patterns, through constructors, factory methods, and deconstructors.
The Future of Java: Records, Sealed Classes and Pattern MatchingJosé Paumard
The release of the JDK 17 brings interesting features in the Java language: sealed types and pattern matching for switch. Along with the introduction of records, the implementation of pattern matching in the Java language begins to take shape. This presentation shows you how records, sealed types, and pattern matching can change the way we write Java code, on real patterns. It also shows you what we can expect to see on this topic in the future. It is mostly a live coding presentation, with some slides when the code is shown cannot be executed.
The features released between Java 11 and Java 17 have brought a greater opportunity for developers to improve application development productivity as well and code expressiveness and readability. In this deep-dive session, you will discover all the recent Project Amber features added to the Java language such as Records (including Records serialization), Pattern Matching for `instanceof`, switch expression, sealed classes, and hidden classes. The main goal of the Amber Project is to bring Pattern Matching to the Java platform, which will impact both the language and the JDK APsI. You will discover record patterns, array patterns, as well as deconstruction patterns, through constructors, factory methods, and deconstructors.
You can find the code shown here: https://github.com/JosePaumard/devoxx-uk-2021
Designing functional and fluent API: application to some GoF patternsJosé Paumard
These are the slides of my Devnexus 2020 talk. The code is avaiblable on my GitHub account: https://github.com/JosePaumard/devnexus-2020-visitor-lambda. You can see a replay of this talk (in a slightly different version) here: https://youtu.be/gq23w9nycBs
Designing functional and fluent API: example of the Visitor PatternJosé Paumard
This is the slide deck of my talk from Devoxx Belgium 2019. You can watch the video here https://www.youtube.com/watch?v=gq23w9nycBs and get the code here: https://github.com/JosePaumard/devoxx-belgium-2019-visitor-lambda.
Among the patterns from the GoF, the Visitor is probably the more complex to implement. One of the difficulties is that you need to implement it in your object model, leading to complex refactoring for legacy applications. Based on the use of all the nifty tools brought by functional programming: chaining, composition, and partial application, you can implement Visitors without having to change your object model, using a functional and fluent API. This approach can be used to implement other patterns: Builder and Validator. Using this way of designing API leads to readable and robust code, designed following the GoF patterns.
Les slides du Tools in Action que j'ai donné à Devoxx France 2019.
Le JDK est open source et son développement aussi. L'ensemble des nouveautés vit sur des branches Mercurial qui peuvent être téléchargées et compilées à la demande. Cela permet de jouer avec des fonctionnalités encore en chantier, de regarder comment les nouvelles syntaxes fonctionneront, bref, de jouer avec un JDK du futur, qui n'existera peut-être jamais. L'objet de ce tools in action est simple : montrer comment tout ceci fonctionne, de l'installation d'une machine Ubuntu à l'exécution d'un JDK recompilé maison.
Le slide deck de l'Université que nous avons donnée avec Rémi Forax à Devoxx France 2019.
Comme promis, Java sort sa version majeure tous les 6 mois. Le train passe et amène son lot de nouveautés. Parmi elles, certaines sont sorties : une nouvelle syntaxe pour les clauses switch et l'instruction de byte code CONSTANT_DYNAMIC. D'autres sont en chantier, plus ou moins avancé : une nouvelle façon d'écrire des méthodes de façon condensée, un instanceof 'intelligent', des constantes évaluées au moment où elles sont utilisées. Les projets progressent. Loom, et son nouveau modèle de programmation concurrente que l'ont peut tester avec Jetty. Amber, qui introduit les data types et des nouvelles syntaxes. Valhalla, dont les value types donnent leurs premiers résultats. S'il est difficile de prévoir une date de sortie pour ces nouveautés, on sait en revanche qu'une fois prêtes elles sortiront en moins de 6 mois. De tout ceci nous parlerons donc au futur et en public, avec des démonstrations de code, des slides, du code, de la joie et de la bonne humeur !
Slides of the talk we gave with David Delabassee at Oracle Code One 2018.
The FnProject was released about a year ago, proposing new ways to design asynchronous systems in a very flexible way. This tutorial shows you how to set up a Fn Server on a local development machine running Windows with a first simple function. Then we cover the design of multi-functions systems, connected together in an asynchronous way, leveraging the Fn Flow API. This API is first presented, including how it compares to the the Java 8 CompletableFuture API. We then set up a real example made of several functions, producing multiple results and see how we can leverage their asynchronous nature to make a non-blocking system, handling errors in a simple and intuitive way. Most of the examples are shown both on slides and live coding parts.
Avec la version 9 sortie en septembre 2017, Java appuie sur la pédale ! Le rythme des livraisons passe à une version majeure tous les 6 mois. Java 10 est sorti en mars, prochaine version en septembre. Java 10 apporte le 'var' et l'inférence de type pour les variables locales. D'autres nouveautés sont en préparation : les constantes dynamiques, les classes de données, un nouveau switch à base de lambda, des interfaces fermées, de nouvelles choses du coté des génériques et bien plus encore.
Cela viendra-t-il en 11, 12, 15 ? Ne spéculons pas, mais quand ces nouveautés seront prêtes, elles sortiront en quelques mois. On se propose de présenter ces nouveautés, celles qui sont presque prêtes, celles qui seront prêtes bientôt, et celles qui ne seront pas prêtes avant un moment. Quels seront les impacts sur le langage, sur la JVM et donc sur les performances ? Que cela va-t-il nous apporter au quotidien, en tant que développeurs ? Quels seront les nouveaux patterns ? Voici le programme de cette présentation, avec des slides, du code, de la joie et de la bonne humeur !
JAX-RS and CDI Bike the (Reactive) BridgeJosé Paumard
This session explains how JAX-RS and CDI became reactive capable in Java EE 8. We put some new features of JAX-RS 2.1 and CDI 2.0 into perspective and show some reactive patterns to improve your application. Add Java 8 CompletionStage to the mix and this API trio becomes your best bet to easily go reactive without leaving the Java EE train.
The slides of my Java One 2017 talk about the Spliterator Patterns, or, how to extend the Stream API using the Spliterator API.
The video is available on YouTube: https://www.youtube.com/watch?v=xgHGpsubL5M
Les slides de ma présentation à Devoxx France 2017.
Introduite en Java 8, l'API Collector vit dans l'ombre de l'API Stream, ce qui est logique puisqu'un collecteur doit se connecter à un stream pour fonctionner. Le JDK est organisé de sorte que l'on utilise surtout les collectors sur étagère : groupingBy, counting et quelques autres. Ces deux éléments masquent non seulement le modèle de traitement de données des collectors, mais aussi sa puissance et ses performances.
Ces présentation parle des collectors qui existent et qu'il faut connaître, ceux que l'on peut créer, ceux dont on se doute que l'on peut les créer une fois que l'on comprend un peu les choses, et les autres, tant les possibilités offertes par cette API sont illimitées.
ArrayList et LinkedList sont dans un bateauJosé Paumard
Slides de mon université à Devoxx France 2016. Le sujet est la performance des algorithmes d'implémentation de List et leur adéquation avec la structure des CPU actuels.
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
Macroeconomics- Movie Location
This will be used as part of your Personal Professional Portfolio once graded.
Objective:
Prepare a presentation or a paper using research, basic comparative analysis, data organization and application of economic information. You will make an informed assessment of an economic climate outside of the United States to accomplish an entertainment industry objective.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
3. @JosePaumard#J8Stream
It’s all about data processing
Up to 2014: only one tool, the Collection Framework
Also 3rd party API: Common Collections, …
4. @JosePaumard#J8Stream
It’s all about data processing
Up to 2014: only one tool, the Collection Framework
Also 3rd party API: Common Collections, …
From 2014: so many new APIs
7. @JosePaumard#J8Stream
It’s all about data processing
Why so?
Because data processing is more and more important
And more and more complex!
Bigger and bigger amount of data to process
8. @JosePaumard#J8Stream
It’s all about data processing
Why so?
Because data processing is more and more important
And more and more complex!
Bigger and bigger amount of data to process
Controlled response time
9. @JosePaumard#J8Stream
It’s all about data processing
Why so?
Because data processing is more and more important
And more and more complex!
Bigger and bigger amount of data to process
Controlled response time
Complex algorithm
12. @JosePaumard#J8Stream
It’s all about data processing
So data processing needs high level primitives
Able to access data wherever it is
That provides map / filter / reduce functions
13. @JosePaumard#J8Stream
It’s all about data processing
So data processing needs high level primitives
Able to access data wherever it is
That provides map / filter / reduce functions
And efficient implementations of those!
14. @JosePaumard#J8Stream
It’s all about data processing
So data processing needs high level primitives
Able to access data wherever it is
That provides map / filter / reduce functions
And efficient implementations of those!
Most probably implemented in parallel
16. @JosePaumard#J8Stream
Agenda
1) To present two API: the Java 8 Stream API and RxJava
• Fundamentals
• Implemented functionalities
• Patterns!
2) And to compare those APIs
• From the developer point of view
• Performances!
23. @JosePaumard#J8Stream
API Stream
What is a Java 8 Stream?
An object that connects to a source
That does not hold any data
That implements the map / filter / reduce pattern
24. @JosePaumard#J8Stream
API Stream
What is a Java 8 Stream?
An object that connects to a source
That does not hold any data
That implements the map / filter / reduce pattern
A new concept in JDK 8
26. @JosePaumard#J8Stream
API Stream
Example
List<String> list = Arrays.asList("one", "two", "three") ;
list.stream() // creation of a new Stream object
.map(s -> s.toUpperCase())
.max(Comparator.comparing(s -> s.length()))
.ifPresent(s -> System.out.println(s)) ;
27. @JosePaumard#J8Stream
API Stream
Example
List<String> list = Arrays.asList("one", "two", "three") ;
list.stream()
.map(s -> s.toUpperCase()) // to upper case
.max(Comparator.comparing(s -> s.length()))
.ifPresent(s -> System.out.println(s)) ;
28. @JosePaumard#J8Stream
API Stream
Example
List<String> list = Arrays.asList("one", "two", "three") ;
list.stream()
.map(s -> s.toUpperCase())
.max(Comparator.comparing(s -> s.length())) // take the longest s
.ifPresent(s -> System.out.println(s)) ;
29. @JosePaumard#J8Stream
API Stream
Example
List<String> list = Arrays.asList("one", "two", "three") ;
list.stream()
.map(s -> s.toUpperCase())
.max(Comparator.comparing(s -> s.length()))
.ifPresent(s -> System.out.println(s)) ; // and print the result
30. @JosePaumard#J8Stream
API Stream
Example
List<String> list = Arrays.asList("one", "two", "three") ;
list.stream()
.map(String::toUpperCase)
.max(Comparator.comparing(String::length))
.ifPresent(System.out::println) ; // and print the result
31. @JosePaumard#J8Stream
Collectors
We can use collectors
List<Person> list = ... ;
list.stream()
.filter(person -> person.getAge() > 30)
.collect(
Collectors.groupingBy(
Person::getAge, // key extractor
Collectors.counting() // downstream collector
)
) ;
32. @JosePaumard#J8Stream
Collectors
We can use collectors
List<Person> list = ... ;
Map<
list.stream()
.filter(person -> person.getAge() > 30)
.collect(
Collectors.groupingBy(
Person::getAge, // key extractor
Collectors.counting() // downstream collector
)
) ;
33. @JosePaumard#J8Stream
Collectors
We can use collectors
List<Person> list = ... ;
Map<Integer,
list.stream()
.filter(person -> person.getAge() > 30)
.collect(
Collectors.groupingBy(
Person::getAge, // key extractor
Collectors.counting() // downstream collector
)
) ;
34. @JosePaumard#J8Stream
Collectors
We can use collectors
List<Person> list = ... ;
Map<Integer, Long> map =
list.stream()
.filter(person -> person.getAge() > 30)
.collect(
Collectors.groupingBy(
Person::getAge, // key extractor
Collectors.counting() // downstream collector
)
) ;
35. @JosePaumard#J8Stream
Collectors
And we can go parallel!
List<Person> list = ... ;
Map<Integer, Long> map =
list.stream().parallel()
.filter(person -> person.getAge() > 30)
.collect(
Collectors.groupingBy(
Person::getAge, // key extractor
Collectors.counting() // downstream collector
)
) ;
38. @JosePaumard#J8Stream
Sources of a Stream
First patterns to create a Stream
List<Person> people = Arrays.asList(p1, p2, p3);
Stream<Person> stream = people.stream();
39. @JosePaumard#J8Stream
Sources of a Stream
First patterns to create a Stream
List<Person> people = Arrays.asList(p1, p2, p3);
Stream<Person> stream = people.stream();
Stream<Person> stream = Stream.of(p1, p2, p3);
40. @JosePaumard#J8Stream
More patterns
Stream on String
String crazy = "supercalifragilisticexpialidocious";
IntStream letters = crazy.chars();
long count = letters.distinct().count();
41. @JosePaumard#J8Stream
More patterns
Stream on String
String crazy = "supercalifragilisticexpialidocious";
IntStream letters = crazy.chars();
long count = letters.distinct().count();
> count = 15
47. @JosePaumard#J8Stream
More patterns
Stream built on the lines of a file
Stream built the words of a String
String book = "alice-in-wonderland.txt";
Stream<String> lines = Files.lines(Paths.get(book)); // autocloseable
String line = "Alice was beginning to get very tired of";
Stream<String> words = Pattern.compile(" ").splitAsStream(line);
48. @JosePaumard#J8Stream
Flatmap
How to mix both to get all the words of a book?
Function<String, Stream<String>> splitToWords =
line -> Pattern.compile(" ").splitAsStream(line);
Stream<String> lines = Files.lines(path);
Stream<String> words = lines.flatMap(splitToWords);
50. @JosePaumard#J8Stream
Flatmap
Another analysis of the result
Stream<String> words = lines.flatMap(splitToWords);
Map<Integer, Long> map =
words.filter(word -> word.length() > 2)
.map(String::toLowerCase)
// .distinct()
.collect(
Collectors.groupingBy(
String::length,
Collectors.counting()
)
);
51. @JosePaumard#J8Stream
Extracting the max from a Map
Yet another analysis of the result
map.entrySet().stream()
.sorted(
Entry.<Integer, Long>comparingByValue().reversed()
)
.limit(3)
.forEach(System.out::println);
53. @JosePaumard#J8Stream
Connecting a Stream on a source
Connecting a Stream on a non-standard source is possible
A Stream is built on 2 things:
- A spliterator (comes from split and iterator)
- A ReferencePipeline (the implementation)
54. @JosePaumard#J8Stream
Connecting a Stream on a source
The Spliterator is meant to be overriden
public interface Spliterator<T> {
boolean tryAdvance(Consumer<? super T> action) ;
Spliterator<T> trySplit() ;
long estimateSize();
int characteristics();
}
55. @JosePaumard#J8Stream
Connecting a Stream on a source
The Spliterator is meant to be overriden
public interface Spliterator<T> {
boolean tryAdvance(Consumer<? super T> action) ;
Spliterator<T> trySplit(); // not needed for non-parallel processings
long estimateSize(); // can return 0
int characteristics(); // returns a constant
}
56. @JosePaumard#J8Stream
Examples of custom Spliterators
Suppose we have a Stream [1, 2, 3, …]
We want to regroup the elements: [[1, 2, 3], [4, 5, 6], …]
Let us build a GroupingSpliterator to do that
57. @JosePaumard#J8Stream
GroupingSpliterator
[1, 2, 3, 4, 5, …] -> [[1, 2, 3], [4, 5, 6], [7, 8, 9], …]
public class GroupingSpliterator<E> implements Spliterator<Stream<E>> {
private final long grouping ;
private final Spliterator<E> spliterator ;
// implementation
}
GroupingSpliterator<Integer> gs =
new GroupingSpliterator(spliterator, grouping);
62. @JosePaumard#J8Stream
GroupingSpliterator
Build a Stream element by element is done with a
Stream.Builder
Stream.Builder<E> builder = Stream.builder() ;
for (int i = 0 ; i < grouping ; i++) {
spliterator.tryAdvance(element -> builder.add(element);
}
Stream<E> subStream = subBuilder.build(); // [1, 2, 3]
63. @JosePaumard#J8Stream
GroupingSpliterator
How do we know if we are done with the underlying Stream?
Stream.Builder<E> builder = Stream.builder() ;
for (int i = 0 ; i < grouping ; i++) {
spliterator.tryAdvance(
element -> builder.add(element)
);
}
Stream<E> subStream = subBuilder.build(); // [1, 2, 3]
64. @JosePaumard#J8Stream
GroupingSpliterator
How do we know if we are done with the underlying Stream?
Stream.Builder<E> builder = Stream.builder() ;
for (int i = 0 ; i < grouping ; i++) {
spliterator.tryAdvance( // when this call returns false
element -> builder.add(element)
);
}
Stream<E> subStream = subBuilder.build(); // [1, 2, 3]
65. @JosePaumard#J8Stream
GroupingSpliterator
How do we know if we are done with the underlying Stream?
Stream.Builder<E> builder = Stream.builder() ;
boolean finished = false;
for (int i = 0 ; i < grouping ; i++) {
if (spliterator.tryAdvance(element -> builder.add(element)))
finished = true;
}
Stream<E> subStream = subBuilder.build(); // [1, 2, 3]
66. @JosePaumard#J8Stream
GroupingSpliterator
How do we know if we are done with the underlying Stream?
public boolean tryAdvance(Consumer<? super Stream<E>> action) {
Stream.Builder<E> builder = Stream.builder() ;
boolean finished = false;
for (int i = 0 ; i < grouping ; i++) {
if (spliterator.tryAdvance(element -> builder.add(element)))
finished = true;
}
Stream<E> subStream = subBuilder.build(); // [1, 2, 3]
action.accept(subStream) ;
return !finished ;
}
68. @JosePaumard#J8Stream
RollingSpliterator
The tryAdvance() call on the underlying Stream becomes this:
bufferWriteIndex is an AtomicLong
private boolean advanceSpliterator() {
return spliterator.tryAdvance(
element -> {
buffer[bufferWriteIndex.get() % buffer.length] = element ;
bufferWriteIndex.incrementAndGet() ;
});
}
69. @JosePaumard#J8Stream
RollingSpliterator
Building the element streams from the ring buffer:
private Stream<E> buildSubstream() {
Stream.Builder<E> subBuilder = Stream.builder() ;
for (int i = 0 ; i < grouping ; i++) {
subBuilder.add(
(E)buffer[(i + bufferReadIndex.get()) % buffer.length]
) ;
}
bufferReadIndex.incrementAndGet() ;
Stream<E> subStream = subBuilder.build() ;
return subStream ;
}
75. @JosePaumard#J8Stream
Spliterator on Spliterators
We then need to implement tryAdvance()
Where transform is a BiFunction
public boolean tryAdvance(Consumer<? super R> action) {
return spliterator1.tryAdvance(
e1 -> {
spliterator2.tryAdvance(e2 -> {
action.accept(tranform.apply(e1, e2)) ;
}) ;
}) ;
}
76. @JosePaumard#J8Stream
ZippingSpliterator
What about creating a Builder for this Spliterator?
ZippingSpliterator.Builder<String, String, String> builder =
new ZippingSpliterator.Builder();
ZippingSpliterator<String,String,String> zippingSpliterator = builder
.with(spliterator1)
.and(spliterator2)
.mergedBy((e1, e2) -> e1 + " - " + e2)
.build();
78. @JosePaumard#J8Stream
What did we do with Streams so far?
We took one stream and built a stream by regrouping its
elements in some ways
79. @JosePaumard#J8Stream
What did we do with Streams so far?
We took one stream and built a stream by regrouping its
elements in some ways
We took to streams and we merged them, element by
element, using a bifunction
80. @JosePaumard#J8Stream
What did we do with Streams so far?
We took one stream and built a stream by regrouping its
elements in some ways
We took to streams and we merged them, element by
element, using a bifunction
What about taking one element at a time, from different
streams?
84. @JosePaumard#J8Stream
What did we do with Streams so far?
We took one stream and built a stream by regrouping its
elements in some ways
We took to streams and we merged them, element by
element, using a bifunction
We took a collection of streams and built a stream by taking
elements from them, in a given order
85. @JosePaumard#J8Stream
Wrap-up for the Stream API
The Java 8 Stream API is not just about implementing map /
filter / reduce of building hashmaps
We can use it to manipulate data in advanced ways:
- by deciding on what source we want to connect
- by deciding how we can consume the data from that source
87. @JosePaumard#J8Stream
RxJava
Open source API, available on Github
Developed by Netflix
RxJava is the Java version of ReactiveX
.NET
Python, Kotlin, JavaScript, Scala, Ruby, Groovy, Rust
Android
https://github.com/ReactiveX/RxJava
92. @JosePaumard#J8Stream
RxJava
The central class is the Observable class
It’s big: ~10k lines of code
It’s complex: ~100 static methods, ~150 non-static methods
It’s complex: not only because there is a lot of things in it, but
also because the concepts are complex
97. @JosePaumard#J8Stream
How to subscribe
Subscribing to an observable
Observable<T> observable = ... ;
Subscription subscription = observable.subscribe(observer) ;
public interface Subscription {
public void unsubscribe();
public void isUnsubscribe();
}
99. @JosePaumard#J8Stream
The usual ways
Observable from collections and arrays
Observable<String> obs1 = Observable.just("one", "two", "three") ;
List<String> strings = Arrays.asList("one", "two", "three") ;
Observable<String> obs2 = Observable.from(strings) ;
100. @JosePaumard#J8Stream
The usual ways
Observable useful for tests
Observable<String> empty = Observable.empty() ;
Observable<String> never = Observable.never() ;
Observable<String> error = Observable.<String>error(exception) ;
101. @JosePaumard#J8Stream
The usual ways
Series and time series
Observable<Long> longs = Observable.range(1L, 100L) ;
// interval
Observable<Long> timeSerie1 =
Observable.interval(1L, TimeUnit.MILLISECONDS) ; // a serie of longs
// initial delay, then interval
Observable<Long> timeSerie2 =
Observable.timer(10L, 1L, TimeUnit.MILLISECONDS) ; // one 0
102. @JosePaumard#J8Stream
The usual ways
The using() method
public final static <T, Resource> Observable<T> using(
final Func0<Resource> resourceFactory, // producer
final Func1<Resource, Observable<T>> observableFactory, // function
final Action1<? super Resource> disposeAction // consumer
) { }
103. @JosePaumard#J8Stream
The usual ways
The using() method
public final static <T, Resource> Observable<T> using(
final Func0<Resource> resourceFactory, // producer
final Func1<Resource, Observable<T>> observableFactory, // function
final Action1<? super Resource> disposeAction // consumer
) { }
104. @JosePaumard#J8Stream
How using() works
1) a resource is created using the resourceFactory
2) an observable is created from the resource using the
observableFactory
3) this observable is further decorated with actions for
exception handling
105. @JosePaumard#J8Stream
RxJava & executors
Some of those methods take a further argument
Scheduler is an interface (in fact an abstract class, to define
« default methods » in Java 7)
Schedulers should be used to create schedulers
Observable<Long> longs = Observable.range(0L, 100L, scheduler) ;
106. @JosePaumard#J8Stream
Schedulers
Factory Schedulers
public final class Schedulers {
public static Scheduler immediate() {...} // immediate
public static Scheduler newThread() {...} // new thread
public static Scheduler trampoline() {...} // queued in the current
// thread
}
107. @JosePaumard#J8Stream
Schedulers
Factory Schedulers
public final class Schedulers {
public static Scheduler computation() {...} // computation ES
public static Scheduler io() {...} // IO growing ES
public static Scheduler test() {...}
public static Scheduler from(Executor executor) {...}
}
110. @JosePaumard#J8Stream
A 1st example
A simple example
Observable<Integer> range1To100 = Observable.range(1L, 100L) ;
range1To100.subscribe(System.out::println) ;
111. @JosePaumard#J8Stream
A 1st example
A simple example
Observable<Integer> range1To100 = Observable.range(1L, 100L) ;
range1To100.subscribe(System.out::println) ;
> 1 2 3 4 ... 100
112. @JosePaumard#J8Stream
A 2nd example
A not so simple example
Observable<Integer> timer = Observable.timer(1, TimeUnit.SECONDS) ;
timer.subscribe(System.out::println) ;
113. @JosePaumard#J8Stream
A 2nd example
A not so simple example
Nothing is printed
Observable<Integer> timer = Observable.timer(1, TimeUnit.SECONDS) ;
timer.subscribe(System.out::println) ;
>
114. @JosePaumard#J8Stream
A 2nd example
Let us modify this code
Observable<Integer> timer = Observable.timer(1, TimeUnit.SECONDS) ;
timer.subscribe(() -> {
System.out.println(Thread.currentThread().getName() + " " +
Thread.currentThread().isDaemon()) ;
}) ;
Thread.sleep(2) ;
115. @JosePaumard#J8Stream
A 2nd example
Let us modify this code
Observable<Integer> timer = Observable.timer(1, TimeUnit.SECONDS) ;
timer.subscribe(() -> {
System.out.println(Thread.currentThread().getName() + " " +
Thread.currentThread().isDaemon()) ;
}) ;
Thread.sleep(2) ;
> RxComputationThreadPool-1 - true
117. @JosePaumard#J8Stream
About the 1st & 2nd examples
The first example ran in the main thread
The second example ran in a daemon thread, that does not
prevent the JVM from exiting. Nothing was printed out,
because it did not have the time to be executed.
118. @JosePaumard#J8Stream
About the 1st & 2nd examples
The first example ran in the main thread
The second example ran in a daemon thread, that does not
prevent the JVM from exiting. Nothing was printed out,
because it did not have the time to be executed.
Observable are ran in their own schedulers (executors)
126. @JosePaumard#J8Stream
Observables of Observables
The methods we saw are defined on Iterables of Observables
They are also defined on Observables of Observables
public final static <T> Observable<T> merge(
Iterable<Observable<T>> listOfSequences) { }
public final static <T> Observable<T> merge(
Observable<Observable<T>> sequenceOfSequences) { }
130. @JosePaumard#J8Stream
A 3rd example
A little more tricky
Observable<Integer> range = Observable.range(1, 100) ;
Observable<String> manyStrings =
Observable.combineLatest(
range, Observable.just("one"),
(integer, string) -> string) ;
131. @JosePaumard#J8Stream
A 3rd example
A little more tricky
Observable<Integer> range = Observable.range(1, 100) ;
Observable<String> manyStrings =
Observable.combineLatest(
range, Observable.just("one"),
(integer, string) -> string) ;
> one (and nothing more)
132. @JosePaumard#J8Stream
A 3rd example
A little more tricky
Observable<Integer> range = Observable.range(1, 100) ;
Observable<String> manyStrings =
Observable.combineLatest(
range, Observable.just("one"),
(integer, string) -> string) ;
> one (and nothing more)
Combines two source Observables
by emitting an item that
aggregates
the latest values of each of the
source Observables
each time an item is received from
either of the source Observables,
where this aggregation is defined
by a specified function.
133. @JosePaumard#J8Stream
A 4th example
Ok, so what about this one?
Observable<Integer> timer = Observable.interval(3, TimeUnit.SECONDS) ;
Observable<String> manyStrings =
Observable.combineLatest(
timer, Observable.just("one"),
(integer, string) -> string) ;
134. @JosePaumard#J8Stream
A 4th example
Ok, so what about this one?
Observable<Integer> timer = Observable.interval(3, TimeUnit.SECONDS) ;
Observable<String> manyStrings =
Observable.combineLatest(
timer, Observable.just("one"),
(integer, string) -> string) ;
> one one one one one one ...
135. @JosePaumard#J8Stream
A 4th example
Ok, so what about this one?
It seems that timer does not behave as range…
Observable<Integer> timer = Observable.interval(3, TimeUnit.SECONDS) ;
Observable<String> manyStrings =
Observable.combineLatest(
timer, Observable.just("one"),
(integer, string) -> string) ;
> one one one one one one ...
138. @JosePaumard#J8Stream
Cold and hot observables
And indeed it does not!
Range is cold observable = produces when observed
Timer is a hot observable = produces, observed or not
139. @JosePaumard#J8Stream
Cold and hot observables
And indeed it does not!
Range is cold observable = produces when observed
Timer is a hot observable = produces, observed or not
Be careful, a cold observable can become hot
140. @JosePaumard#J8Stream
Cold and hot observables
An observable can have as many observers as we want
Thus, a cold observable observed by an observer will
generate values according to this observer
If another observer subscribes to it, it will see this observable
as a hot observable
142. @JosePaumard#J8Stream
Cold and hot observables
Problem: what happens if we have many observers to
subscribe?
Our application could miss the first values emitted by an
observable
144. @JosePaumard#J8Stream
Cold and hot observables
We can do better and use a ConnectableObservable
(which is an Observable)
// does not count as a subscription
ConnectableObservable<Long> publish = observable.publish();
// take the time to connect all the observers
// then call
publish.connect();
145. @JosePaumard#J8Stream
Subscribing to an Observable
About 10 different versions of doOnSomething
Each = the 3 callbacks: onNext, onError, onComplete
For instance, onNext() only acts with the onNext callback
doOnEach(Action1<T> onEach) { } // consumer
146. @JosePaumard#J8Stream
Subscribing to an Observable
Map / filter, return an Observable
Emits only the elements that match the predicate
map(Func1<T, R> mapping) { }
cast(Class<R> clazz) { } // casts the elements
filter(Func1<T, Boolean> predicate) { }
147. @JosePaumard#J8Stream
Subscribing to an Observable
Materialize: special type of mapping
Emit a Notification object that wraps the item, with metadata
Useful for logging
Does the reverse:
materialize() { } // Observable<Notification<T>>
dematerialize() { } // Observable<T>
149. @JosePaumard#J8Stream
Subscribing to an Observable
Special functions
Emits a true then complete on the onComplete
if the Observable emitted at least one item
exists(Func1<T, Boolean> predicate) { }
150. @JosePaumard#J8Stream
Subscribing to an Observable
Special functions
Emits the nth item then complete on the onNext
if the Observable emitted at least n items
elementAt(int n) { }
152. @JosePaumard#J8Stream
Subscribing to an Observable
Special functions
Emits the first item on the onComplete
or emits an error on the second item emitted
single() { }
153. @JosePaumard#J8Stream
Subscribing to an Observable
Special functions
Emits the matching item if it has been seen, on onComplete
or emits an error if not, on onComplete
single(Func1<T, Boolean> predicate) { }
155. @JosePaumard#J8Stream
Reductions & collections
Accumulations
Reduce: returns the reduction of all the items, on onComplete
Scan: returns the reduction step by step, on onNext
reduce(Func2<T, T, T> accumulator) { } // Observable<T>
scan(Func2<T, T, T> accumulator) { } // Observable<T>
156. @JosePaumard#J8Stream
Reductions & collections
Collecting data in a mutable container
Example: adding the elements to a list
collect(Func0<R> stateFactory, // producer
Action2<R, T> collector) { } // BiConsumer
collect(ArrayList::new, // producer
ArrayList::add) { } // BiConsumer
160. @JosePaumard#J8Stream
Reductions & collections
A special kind of map:
The returned observable could hold a single map,
but it does not
It holds GroupedObservable items, which holds its key
groupBy(Func1<T, K> keySelector) { } // function
161. @JosePaumard#J8Stream
Repeating & retrying
The repeat method repeats the same Observable
repeat() { } // Observable<T>
repeat(long times) { } // Observable<T>
repeatWhen(
Func1<Observable<Void>>, Observable<?>> notificationHandler
) { }
162. @JosePaumard#J8Stream
Repeating & retrying
repeat: will repeat the same Observable again and again
On the returned Observable, one can invoke:
onComplete() or onError(), which will trigger the same call on
the source Observable
onNext(), that triggers the repetition
163. @JosePaumard#J8Stream
Repeating & retrying
The retry method will reset the Observable on error
retry() { } // Observable<T>
retry(long times) { } // Observable<T>
retryWhen(
Func1<Observable<Throwable>>, Observable<?>> notificationHandler
) { }
164. @JosePaumard#J8Stream
Joining
Joins to Observable, based on the overlapping of durations
join(Observable<TRight> right,
Func1<T, Observable<TLeftDuration>> leftDurationSelector,
Func1<TRight, Observable<TRightDuration>> rightDurationSelector,
Func2<T, TRight, R> resultSelector) { }
166. @JosePaumard#J8Stream
GroupJoin
Joins to Observable, based on the overlapping of durations
groupJoin(
Observable<T2> right,
Func1<? super T, ? extends Observable<D1>> leftDuration,
Func1<? super T2, ? extends Observable<D2>> rightDuration,
Func2<? super T, ? super Observable<T2>, ? extends R> resultSelector)
{ }
168. @JosePaumard#J8Stream
Dealing with the time
RxJava has a set of methods to deal with time
Let us go back on our cold / hot Observables
It is easy to imagine a hot Observable that emits an onNext
event each second, thus playing the role of a clock
172. @JosePaumard#J8Stream
Measuring time
If we can measure time, then we can emit it
Will emit an the amount of time between the two last onNext
events
timeInterval() { } // Observable<TimeInterval<T>>
173. @JosePaumard#J8Stream
Measuring time
If we can measure time, then we can delay an emission
Will reemit the items, with a delay
This delay can be computed from the items themselves
delay(long delay, TimeUnit timeUnit) ; // Observable<T>
delay(Func1<T, Observable<U> func1) ; // Observable<T>
174. @JosePaumard#J8Stream
Measuring time
If we can measure time, then we can timeout
Will emit an error if no item is seen during this time
timeout(long n, TimeUnit timeUnit) { }
176. @JosePaumard#J8Stream
Fast hot observables
What happens if a hot Observable emits too many items?
What happens when an Observer cannot keep up the pace of
an Observable?
This leads to the notion of backpressure
178. @JosePaumard#J8Stream
Buffering
Buffering records data in a buffer and emits it
buffer(int size) { } // Observable<List<T>>
buffer(long timeSpan, TimeUnit unit) { } // Observable<List<T>>
buffer(long timeSpan, TimeUnit unit, int maxSize) { }
179. @JosePaumard#J8Stream
Buffering
Buffering records data in a buffer (a list) and emits it
buffer(int size) { } // Observable<List<T>>
buffer(long timeSpan, TimeUnit unit) { } // Observable<List<T>>
buffer(long timeSpan, TimeUnit unit, int maxSize) { }
buffer(Observable<O> bufferOpenings, // Openings events
Func1<O, Observable<C>> bufferClosings) { } // Closings events
180. @JosePaumard#J8Stream
Windowing
Windowing acts as a buffer, but emits Observables instead of
lists of buffered items
window(int size) { } // Observable<Observable<T>>
window(long timeSpan, TimeUnit unit) { } // Observable<Observable<T>>
window(long timeSpan, TimeUnit unit, int maxSize) { }
window(Observable<O> bufferOpenings, // Openings events
Func1<O, Observable<C>> bufferClosings) { } // Closings events
183. @JosePaumard#J8Stream
Throttling
Throttling is a sampler on the beginning or the end of a
window
throttleFirst(long windowDuration, TimeUnit unit) { } // Observable<T>
throttleLast(long windowDuration, TimeUnit unit) { }
throttleWithTimeout(long windowDuration, TimeUnit unit) { }
185. @JosePaumard#J8Stream
Debouncing
Debounce also limits the rate of the emission of the items, by
adding a delay before reemitting
debounce(long delay, TimeUnit timeUnit) ; // Observable<T>
debounce(Func1<T, Observable<U> func1) ; // Observable<T>
187. @JosePaumard#J8Stream
Wrap-up on RxJava
Complex API, many different concepts, many methods
Allows to process data in chosen threads, this is useful for IO,
computations, specialized threads (GUI threads)
Allows the synchronization of operations
on clocks
on application events
Works in pull mode, and also in push mode
backpressure
190. @JosePaumard#J8Stream
Getting the best of both API?
If we have an Iterator, this is easy:
Iterator<T> iterator = ... ;
Observable<T> observable = Observable.from(() -> iterator) ;
191. @JosePaumard#J8Stream
Getting the best of both API?
If we have an Iterator, this is easy:
If we have a Spliterator, not much more complex:
Iterator<T> iterator = ... ;
Observable<T> observable = Observable.from(() -> iterator) ;
Spliterator<T> spliterator = ... ;
Observable<T> observable =
Observable.from(() -> Spliterators.iterator(spliterator)) ;
194. @JosePaumard#J8Stream
Getting the best of both API?
So if we have a Stream, we can easily build an Observable
What about the other way?
1) We can build an Iterator on an Observable
2) Then build a Spliterator on an Iterator
195. @JosePaumard#J8Stream
Getting the best of both API?
So if we have a Stream, we can easily build an Observable
What about the other way?
1) We can build an Iterator on an Observable
2) Then build a Spliterator on an Iterator
But we need to do that ourselves…
196. @JosePaumard#J8Stream
Iterating on an Observable
To implement an Iterator:
1) We need to implement next() and hasNext()
2) remove() is a default method in Java 8
197. @JosePaumard#J8Stream
Iterating on an Observable
The trick is that
an iterator pulls the date from a source
an observable pushes the data to callbacks
198. @JosePaumard#J8Stream
Iterating on an Observable
The trick is that
an iterator pulls the date from a source
an observable pushes the data to callbacks
So we need an adapter…
199. @JosePaumard#J8Stream
Iterating on an Observable
How has it been done in the JDK?
public static<T> Iterator<T>
iterator(Spliterator<? extends T> spliterator) {
class Adapter implements Iterator<T>, Consumer<T> {
// implementation
}
return new Adapter() ;
}
200. @JosePaumard#J8Stream
class Adapter implements Iterator<T>, Consumer<T> {
boolean valueReady = false ;
T nextElement;
public void accept(T t) {
valueReady = true ;
nextElement = t ;
}
public boolean hasNext() {
if (!valueReady)
spliterator.tryAdvance(this) ; // calls accept()
return valueReady ;
}
public T next() {
if (!valueReady && !hasNext())
throw new NoSuchElementException() ;
else {
valueReady = false ;
return nextElement ;
}
}
}
201. @JosePaumard#J8Stream
Iterating on an Observable
Let us adapt this pattern!
public static<T> Iterator<T>
of(Observable<? extends T> observable) {
class Adapter implements Iterator<T> {
// implementation
}
return new Adapter() ;
}
202. @JosePaumard#J8Stream
class Adapter implements Iterator<T>, Consumer<T> {
boolean valueReady = false ;
T nextElement;
public void accept(T t) { // needs to be called by the Observable
valueReady = true ;
nextElement = t ;
}
public boolean hasNext() {
return valueReady ;
}
public T next() {
if (!valueReady && !hasNext())
throw new NoSuchElementException() ;
else {
valueReady = false ;
return nextElement ;
}
}
}
203. @JosePaumard#J8Stream
Iterating on an Observable
The accept method
class Adapter implements Iterator<T>, Consumer<T> {
boolean valueReady = false ;
T nextElement;
public void accept(T t) {
observable.subscribe(
element -> nextElement = element, // onNext
exception -> valueReady = false, // onError
() -> valueReady = false // onComplete
) ;
}
}
204. @JosePaumard#J8Stream
Iterating on an Observable
The accept method
class Adapter implements Iterator<T>, Consumer<T> {
boolean valueReady = false ;
T nextElement;
public void accept(T t) {
observable.subscribe(
element -> nextElement = element, // onNext
exception -> valueReady = false, // onError
() -> valueReady = false // onComplete
) ;
}
}
final…
205. @JosePaumard#J8Stream
Iterating on an Observable
We can wrap those value in Atomic variable
class Adapter implements Iterator<T>, Consumer<T> {
AtomicBoolean valueReady = new AtomicBoolean(false) ;
AtomicReference<T> nextElement = new AtomicReference() ;
public void accept(T t) {
observable.subscribe(
element -> nextElement.set(element), // onNext
exception -> valueReady.set(false), // onError
() -> valueReady.set(false) // onComplete
) ;
}
}
207. @JosePaumard#J8Stream
Iterating on an Observable
Cant we do better?
interface Wrapper<E> {
E get() ;
}
Wrapper<Boolean> wb = () -> true ;
Action1<Boolean> onNext = b -> wb.set(b) ; // should return Wrapper<T>
208. @JosePaumard#J8Stream
Iterating on an Observable
Cant we do better?
interface Wrapper<E> {
E get() ;
public default Wrapper<E> set(E e) {
// should return a wrapper of e
}
}
Wrapper<Boolean> wb = () -> true ;
Action1<Boolean> onNext = b -> wb.set(b) ; // should return Wrapper<T>
209. @JosePaumard#J8Stream
Iterating on an Observable
Cant we do better?
interface Wrapper<E> {
E get() ;
public default Wrapper<E> set(E e) {
return () -> e ;
}
}
Wrapper<Boolean> wb = () -> true ;
Action1<Boolean> onNext = b -> wb.set(b) ; // should return Wrapper<T>
210. @JosePaumard#J8Stream
Iterating on an Observable
We can wrap those value in Atomic variable
class Adapter implements Iterator<T>, Consumer<T> {
Wrapper<Boolean> valueReady = () -> false ;
Wrapper<T> nextElement ;
public void accept(T t) {
observable.subscribe(
element -> nextElement.set(element), // onNext
exception -> valueReady.set(false), // onError
() -> valueReady.set(false) // onComplete
) ;
}
}
211. @JosePaumard#J8Stream
Iterating on an Observable
So we can build an Iterator on an Observable
And with it, a Spliterator on an Observable
it will work on cold observables
212. @JosePaumard#J8Stream
Getting the best of both API
The cold observables can be implemeted with Java 8 Streams
The hot observables can be implemented by combining both
API
214. @JosePaumard#J8Stream
Let us do some comparisons
Let us take one use case
Implemented in Rx and J8 Streams
See the different ways of writing the same processings
And compare the processing times using JMH
215. @JosePaumard#J8Stream
Shakespeare plays Scrabble
Published in Java Magazine
Presented in Java One 2014
Used during Virtual Technology Summit
https://community.oracle.com/docs/DOC-916777
https://github.com/JosePaumard/jdk8-lambda-tour
217. @JosePaumard#J8Stream
Shakespeare plays Scrabble
1) Build the histogram of the letters of a word
2) Number of blanks needed for a letter in a word
3) Number of blanks needed to write a word
4) Predicate to check is a word can be written with 2 blanks
5) Bonus for a doubled letter
6) Final score of a word
7) Histogram of the scores
8) Best word
218. @JosePaumard#J8Stream
1) Histogram of the letters
Java 8 Stream API – Rx Java
// Histogram of the letters in a given word
Function<String, Map<Integer, Long>> histoOfLetters =
word -> word.chars().boxed()
.collect(
Collectors.groupingBy(
Function.identity(),
Collectors.counting()
)
) ;
219. @JosePaumard#J8Stream
1) Histogram of the letters
Java 8 Stream API – Rx Java
// Histogram of the letters in a given word
Func1<String, Observable<HashMap<Integer, LongWrapper>>> histoOfLetters =
word -> toIntegerObservable.call(word)
.collect(
() -> new HashMap<Integer, LongWrapper>(),
(HashMap<Integer, LongWrapper> map, Integer value) -> {
LongWrapper newValue = map.get(value) ;
if (newValue == null) {
newValue = () -> 0L ;
}
map.put(value, newValue.incAndSet()) ;
}) ;
220. @JosePaumard#J8Stream
1) Histogram of the letters
Java 8 Stream API – Rx Java
interface LongWrapper {
long get() ;
public default LongWrapper set(long l) {
return () -> l ;
}
public default LongWrapper incAndSet() {
return () -> get() + 1L ;
}
public default LongWrapper add(LongWrapper other) {
return () -> get() + other.get() ;
}
}
221. @JosePaumard#J8Stream
2) # of blanks for a letter
Java 8 Stream API – Rx Java
// number of blanks for a given letter
ToLongFunction<Map.Entry<Integer, Long>> blank =
entry ->
Long.max(
0L,
entry.getValue() -
scrabbleAvailableLetters[entry.getKey() - 'a']
) ;
222. @JosePaumard#J8Stream
2) # of blanks for a letter
Java 8 Stream API – Rx Java
// number of blanks for a given letter
Func1<Entry<Integer, LongWrapper>, Observable<Long>> blank =
entry ->
Observable.just(
Long.max(
0L,
entry.getValue().get() -
scrabbleAvailableLetters[entry.getKey() - 'a']
223. @JosePaumard#J8Stream
3) # of blanks for a word
Java 8 Stream API – Rx Java
// number of blanks for a given word
Function<String, Long> nBlanks =
word -> histoOfLetters.apply(word)
.entrySet().stream()
.mapToLong(blank)
.sum();
224. @JosePaumard#J8Stream
3) # of blanks for a word
Java 8 Stream API – Rx Java
// number of blanks for a given word
Func1<String, Observable<Long>> nBlanks =
word -> histoOfLetters.call(word)
.flatMap(map -> Observable.from(() ->
map.entrySet().iterator()))
.flatMap(blank)
.reduce(Long::sum) ;
225. @JosePaumard#J8Stream
4) Predicate for 2 blanks
Java 8 Stream API – Rx Java
// can a word be written with 2 blanks?
Predicate<String> checkBlanks = word -> nBlanks.apply(word) <= 2 ;
// can a word be written with 2 blanks?
Func1<String, Observable<Boolean>> checkBlanks =
word -> nBlanks.call(word)
.flatMap(l -> Observable.just(l <= 2L)) ;
226. @JosePaumard#J8Stream
5) Bonus for a doubled letter – 1
Java 8 Stream API – Rx Java
// Placing the word on the board
// Building the streams of first and last letters
Function<String, IntStream> first3 =
word -> word.chars().limit(3);
227. @JosePaumard#J8Stream
5) Bonus for a doubled letter – 1
Java 8 Stream API – Rx Java
// Placing the word on the board
// Building the streams of first and last letters
Func1<String, Observable<Integer>> first3 =
word ->
Observable.from(
IterableSpliterator.of(
word.chars().boxed().limit(3).spliterator()
)
) ;
228. @JosePaumard#J8Stream
5) Bonus for a doubled letter – 2
Java 8 Stream API – Rx Java
// Bonus for double letter
ToIntFunction<String> bonusForDoubleLetter =
word -> Stream.of(first3.apply(word), last3.apply(word))
.flatMapToInt(Function.identity())
.map(scoreOfALetter)
.max()
.orElse(0) ;
229. @JosePaumard#J8Stream
5) Bonus for a doubled letter – 2
Java 8 Stream API – Rx Java
// Bonus for double letter
Func1<String, Observable<Integer>> bonusForDoubleLetter =
word -> Observable.just(first3.call(word), last3.call(word))
.flatMap(observable -> observable)
.flatMap(scoreOfALetter)
.reduce(Integer::max) ;
230. @JosePaumard#J8Stream
6) Final score of a word
Java 8 Stream API – Rx Java
// score of the word put on the board
Function<String, Integer> score3 =
word ->
2*(score2.apply(word)
+ bonusForDoubleLetter.applyAsInt(word))
+ (word.length() == 7 ? 50 : 0);
231. @JosePaumard#J8Stream
6) Final score of a word
Java 8 Stream API – Rx Java
// score of the word put on the board
Func1<String, Observable<Integer>> score3 =
word ->
Observable.just(
score2.call(word), score2.call(word),
bonusForDoubleLetter.call(word),
bonusForDoubleLetter.call(word),
Observable.just(word.length() == 7 ? 50 : 0)
)
.flatMap(observable -> observable)
.reduce(Integer::sum) ;
232. @JosePaumard#J8Stream
7) Histogram of the scores
Java 8 Stream API – Rx Java
Function<Function<String, Integer>, Map<Integer, List<String>>>
buildHistoOnScore =
score -> shakespeareWords.stream().parallel()
.filter(scrabbleWords::contains)
.filter(checkBlanks)
.collect(
Collectors.groupingBy(
score,
() -> new TreeMap<>(Comparator.reverseOrder()),
Collectors.toList()
)
) ;
233. @JosePaumard#J8Stream
7) Histogram of the scores
Java 8 Stream API – Rx Java
Func1<Func1<String, Observable<Integer>>, Observable<TreeMap<Integer, List<String>>>>
buildHistoOnScore =
score -> Observable.from(() -> shakespeareWords.iterator())
.filter(scrabbleWords::contains)
.filter(word -> checkBlanks.call(word).toBlocking().first())
.collect(
() -> new TreeMap<Integer, List<String>>(Comparator.reverseOrder()),
(TreeMap<Integer, List<String>> map, String word) -> {
Integer key = score.call(word).toBlocking().first() ;
List<String> list = map.get(key) ;
if (list == null) {
list = new ArrayList<String>() ;
map.put(key, list) ;
}
list.add(word) ;
}) ;
234. @JosePaumard#J8Stream
8) Best word
Java 8 Stream API – Rx Java
// best key / value pairs
List<Entry<Integer, List<String>>> finalList =
buildHistoOnScore.apply(score3).entrySet()
.stream()
.limit(3)
.collect(Collectors.toList()) ;
235. @JosePaumard#J8Stream
8) Best word
Java 8 Stream API – Rx Java
// best key / value pairs
List<Entry<Integer, List<String>>> finalList2 =
buildHistoOnScore.call(score3)
.flatMap(map -> Observable.from(() -> map.entrySet().iterator()))
.take(3)
.collect(
() -> new ArrayList<Entry<Integer, List<String>>>(),
(list, entry) -> { list.add(entry) ; }
)
.toBlocking()
.first() ;
236. @JosePaumard#J8Stream
8) Best word
Java 8 Stream API – Rx Java
// best key / value pairs
CountDownLatch latch = new CountDownLatch(3) ;
buildHistoOnScore.call(score3)
.flatMap(map -> Observable.from(() -> map.entrySet().iterator()))
.take(3)
.collect(
() -> new ArrayList<Entry<Integer, List<String>>>(),
(list, entry) -> { list.add(entry) ; latch.countDown() ; }
)
.forEach(...) ;
latch.await() ;
237. @JosePaumard#J8Stream
Patterns comparison
Java 8 Stream API: clean, simple, factory methods for
Collectors
RxJava: flatMap calls, lack of factory methods
Java 8 can easily go parallel, which is a plus
238. @JosePaumard#J8Stream
Performances
Let us use JMH
Standard tool for measuring code performance on the JVM
Developed as an Open JDK tool
By Aleksey Shipilev http://shipilev.net/
https://twitter.com/shipilev
http://openjdk.java.net/projects/code-tools/jmh/
http://openjdk.java.net/projects/code-tools/jcstress/
https://www.parleys.com/tutorial/java-microbenchmark-harness-the-lesser-two-evils
239. @JosePaumard#J8Stream
Performances
Let us use JMH
Standard tool for measuring code performance on the JVM
Developed as an Open JDK tool
By Aleksey Shipilev http://shipilev.net/
https://twitter.com/shipilev
http://openjdk.java.net/projects/code-tools/jmh/
http://openjdk.java.net/projects/code-tools/jcstress/
https://www.parleys.com/tutorial/java-microbenchmark-harness-the-lesser-two-evils
Aleksey Shipilëv @shipilev
Чувак из ТВ-службы пришёл отключать
антенну. Оказался масс-
спектрометристом, сцепился языком с
тестем: стоят, обсуждают девайсы.
#наукоград
247. @JosePaumard#J8Stream
Performances
Average execution time
RxJava spends a lot of time openning observables, due to the
all flatMap patterns
Benchmark Mode Cnt Score Error Units
NonParallelStreams avgt 100 29,027 ± 0,279 ms/op
RxJava avgt 100 253,788 ± 1,421 ms/op
ParallelStreams avgt 100 7,624 ± 0,055 ms/op
249. @JosePaumard#J8Stream
Conclusion
Functional programming is in the mood
From the pure performance point of view, things are not that
simple
Java 8 Streams have adopted a partial functional approach,
which is probably a good trade off
250. @JosePaumard#J8Stream
Conclusion
RxJava: rich and complex API
many patterns are available in Java 8 Streams
can run in Java 7 applications
the « push » approach is very interesting
choose your use case carefully, to avoir performance hits
http://www.reactive-streams.org/
http://reactivex.io/
https://github.com/reactive-streams/
252. @JosePaumard#J8Stream
Conclusion
With more to come in Java 9
Java 9 is bringing a reactive framework as part of
java.util.concurrent
http://openjdk.java.net/jeps/266
http://gee.cs.oswego.edu/dl/jsr166/dist/docs/index.html (Class Flow)