The document discusses testing JavaFX applications using TestFX and JUnit. It provides a simple "Hello World" JavaFX application example and extracts the application logic into separate classes that can be tested independently. This allows testing the logic with JUnit unit tests while avoiding the need to launch the full JavaFX application. The document also recommends using JMH microbenchmarks to test the performance of application services as part of a Test Driven Development approach.
Proxy Deep Dive JUG Saxony Day 2015-10-02Sven Ruppert
Ein wenig über Proxy´s. Wer mehr Hintergrundinfos dazu haben möchte, empfehle ich das Buch von Dr. Kabutz und mir :
http://www.amazon.de/Dynamic-Proxies-Dr-Heinz-Kabutz/dp/3868021531/ref=asap_bc?ie=UTF8
How a migration to MicroServices could change the team, architecture and coding culture.
What you could you do and how you could transform a "Jurassic Park" into a lightweight environment.
In this talk we will explore the strategy, techniques, pattern and tools I used to
transform a team and the architecture that was grown over 15yrs.
This will be a mix of pattern, tools and techniques that was able to migrate
old systems, used inside insurance and banks.
Dependency Injection is now part of nearly every Java project. But what is the difference between DI and CDI. How to decide what I could use better, what frameworks are available and what are the differences for me as a programmer? What could be an option for the IoT-, Desktop- or Webproject?
In this talk we will get an overview over different frameworks and how they are working. We are not checking the well known big one only, but we are looking at some small sometimes specialized implementations.
Everybody knows the pattern proxy, but how can you use it effectively?
What kind of proxy patterns are available, and how can you
build patterns more effectively with it? Why is reflection needed for this?
Importantly, we need only the core JDK in most cases.
This tutorial starts from the basics and continues on to
DynamicProxies, DynamicObjectAdapter and DynamicStaticProxies at runtime, StaticObjectAdapters, and more.
The session, based on the German book Dynamic Proxies,
by Heinz Kabutz and the session’s presenter, takes a deep dive into this pattern group.
The document discusses testing JavaFX applications using TestFX and JUnit. It provides a simple "Hello World" JavaFX application example and extracts the application logic into separate classes that can be tested independently. This allows testing the logic with JUnit unit tests while avoiding the need to launch the full JavaFX application. The document also recommends using JMH microbenchmarks to test the performance of application services as part of a Test Driven Development approach.
Proxy Deep Dive JUG Saxony Day 2015-10-02Sven Ruppert
Ein wenig über Proxy´s. Wer mehr Hintergrundinfos dazu haben möchte, empfehle ich das Buch von Dr. Kabutz und mir :
http://www.amazon.de/Dynamic-Proxies-Dr-Heinz-Kabutz/dp/3868021531/ref=asap_bc?ie=UTF8
How a migration to MicroServices could change the team, architecture and coding culture.
What you could you do and how you could transform a "Jurassic Park" into a lightweight environment.
In this talk we will explore the strategy, techniques, pattern and tools I used to
transform a team and the architecture that was grown over 15yrs.
This will be a mix of pattern, tools and techniques that was able to migrate
old systems, used inside insurance and banks.
Dependency Injection is now part of nearly every Java project. But what is the difference between DI and CDI. How to decide what I could use better, what frameworks are available and what are the differences for me as a programmer? What could be an option for the IoT-, Desktop- or Webproject?
In this talk we will get an overview over different frameworks and how they are working. We are not checking the well known big one only, but we are looking at some small sometimes specialized implementations.
Everybody knows the pattern proxy, but how can you use it effectively?
What kind of proxy patterns are available, and how can you
build patterns more effectively with it? Why is reflection needed for this?
Importantly, we need only the core JDK in most cases.
This tutorial starts from the basics and continues on to
DynamicProxies, DynamicObjectAdapter and DynamicStaticProxies at runtime, StaticObjectAdapters, and more.
The session, based on the German book Dynamic Proxies,
by Heinz Kabutz and the session’s presenter, takes a deep dive into this pattern group.
The document discusses mutation testing as a way to write better unit tests. Mutation testing involves making small changes or "mutations" to the production code and then running the test suite to see if the tests can detect the changes, or "kill" the mutations. It is recommended to generate mutants, run the unit tests, check the reports, and write more or improved tests until reaching a quality target where most or all mutants are killed. Different types of common code mutations are discussed such as replacing operators, variables, or removing conditionals. The goal of mutation testing is to help write a test suite that can detect as many small defects as possible in the code.
At this talk we will start from the basics and come shortly to DynamicProxies, generated type-save DynamicObjectAdapterBuilder and more. We will have a deep dive to this pattern group , and I am sure you will like it ;-)
This talk is based on the german book "Dynamic Proxies" written from Dr. Heinz Kabutz and me.
Dokumen tersebut membahas tentang konsep dasar rangkaian listrik, termasuk definisi rangkaian listrik, komponen listrik aktif dan pasif, arus listrik, tegangan, energi, dan daya. Juga membahas analisis rangkaian dan contoh soal latihan terkait konsep-konsep tersebut.
http://www.jug.ch/html/events/2014/javafx_jumpstart.html
JavaFX - nun endlich ist es soweit. Swing ist offiziell seit Java8 im reinen Wartungsmodus, JavaFX ist der Nachfolger und nun endlich Teil des JDK. Also alles deutet auf neue Zeiten in der Desktopentwicklung hin.. ABER..
Wie kann ich mit JavaFX beginnen?
Wie kann ich es mit Swing Projekten kombinieren?
Gibt es Test-Tools?
Wie beginne ich mit der Migration von Swing auf JavaFX?
Diese oder ähnliche Fragen stellen sich zu Beginn der Arbeit mit JavaFX
Wir werden uns den Start mit JavaFX, Werkzeuge wie TestFX und Kombinationen mit CDI und Swing ansehen.
This document discusses strategies that elites can use to maintain their dominance through soft power. It defines elites as the top 1% who control 40% of the world's wealth and benefit most from the existing power structures. The document presents two main micro-level soft power strategies used by elites: 1) Promoting the idea of personal responsibility to suggest that inequality results from individual choices rather than systemic factors, and 2) Perpetuating the illusion that equality of opportunity exists by highlighting examples of individuals who rose from humble beginnings. It argues that elites in the US rely more on "smart soft power" through subtle manipulation of identities and beliefs rather than overt hard power, allowing them to control society with less repression.
N.Chandrashekar has over 16 years of experience in supply chain management, procurement, inventory control, and logistics. He is currently a Senior Stores Officer at Opto Circuits India Limited in Visakhapatnam, where he is responsible for vendor management, inventory management, and logistics management. He seeks to utilize his strengths in these areas for a reputed organization.
Warum empfehle ich meinen Kunden das Spring Framework? Michael Plöd
In den letzten Jahren wurde vermehrt die Diskussion JEE 6 vs. Spring geführt, wobei immer öfter die Irrelevanz des Spring Frameworks heraufbeschworen wurde. Im Rahmen der Session möchte ich - abseits jeglicher Polemik - in einer ganzheitlichen Betrachtung schildern, warum ich meinen Kunden noch immer zum Einsatz von Spring rate.
OSMC 2010 | Java Monitoring und Troubleshooting by Rainer JungNETWAYS
Ein großer Teil der Geschäftslogik von Unternehmen ist heute in Java-Software abgebildet. Dennoch werden Java-Anwendungen nur allzu häufig als Black Box betrieben und die Analyse von Störungen sehr schnell an Entwicklungsabteilungen delegiert. Diesen steht jedoch in der Regel keine für eine Ursachenanalyse ausreichende Informationsbasis zur Verfügung, so dass Operations und Entwicklung sich auf eine langwierige und schmerzhafte Suche machen.
Dabei bietet die Java-Plattform durchaus interessante Möglichkeiten der Überwachung, die eine schnelle Eingrenzung der Wurzelursache erleichtern, aber leider noch zu wenig bekannt sind und kaum genutzt werden. Im Vortrag werden zunächst einige Grundlagen hierfür vorgestellt, insbesondere JMX. Am Beispiel von Apache Tomcat vertiefen wir, welche für das Monitoring sehr spannenden Parameter dort zur Verfügung stehen, aber auch welche Probleme dieser Ansatz mit sich bringt.
Ein kurzer Ausflug in die Analyse von Java-Thread Dumps schließt den Vortrag ab. Thread Dumps sind der wichtigste – das Monitoring ergänzende – Ansatz für das Troubleshooting von Java-Anwendungen, insbesondere wenn es um Performance-Probleme in verteilten Landschaften geht. Nicht zu vergessen: diese Methode kann auch in Produktion verwendet werden.
Ein Blick in die Kristallkugel mit dem Ziel spannende und relevante Online-Trends für das Jahr 2003 hervorzusagen. Auf der Liste sind:
- JSP 2.0
- XHTML 2
- Platform for Privacy Preferences
- Watermarking
- C#
- Multimedia Home Platform
- Semantic Web
- WLAN
- XSL-FO
- SVG
The article "JavaFX goes Open Source" was published in the German Java Magazin in May 2013 and discussed JavaFX on iOS and Android with their implementations.
The outlook from May 2013 comes true and showed an architecture diagram, how mobile applications could be created with OpenJFX & OpenJDK by the Java developer community using e.g. RoboVM for iOS.
JPA – Der Persistenz-Standard in der Java EE und SEhwilming
Die Abbildung relationaler Strukturen einer Datenbank auf die objekt‐orientierte Programmiersprache Java bringt einige Herausforderungen mit sich, bekannt als object-relational impedance mismatch. In Java ermöglicht JDBC zwar die Interaktion mir einer relationalen Datenbank aber nicht die Abbildung der Daten auf Objekte. Die bekannten Produkte wie Hibernate oder EclipseLink widmen sich diesem Problem bereits seit Jahren. Mit JPA hat der Java Community Process einen Standard für Java EE und SE definiert, der ein einheitliches API bietet, welches von den Anbietern unterstützt wird. Der Vortrag zeigt was JPA bietet und welche Vorteile der Standard für die Anwendungsentwicklung mit sich bringt.
Testgetriebene Entwicklung mit Jasmine und Karma hat sich mittlerweile schon als defacto-Standard etabliert. Routinen ohne Abhängigkeiten lassen sich damit ohne Probleme testen. Die Schwierigkeiten beginnen jedoch schon, wenn es um die Auflösung von Abhängigkeiten geht. In diesem Vortrag werden verschiedene Strategien und Werkzeuge vorgestellt, mit denen Abhängigkeiten zu Objekten und Funktionen oder zum Server abgedeckt werden können. Aber nicht nur Abhängigkeiten stellen Schwierigkeiten bei der testgetriebenen Entwicklung dar, auch der Umgang mit Fixtures ist bei der testgetriebenen Entwicklung mit JavaScript relevant. Abgerundet wird dieser Vortrag mit einigen Best Practices für die testgetriebenen Entwicklung mit JavaScript.
The document discusses mutation testing as a way to write better unit tests. Mutation testing involves making small changes or "mutations" to the production code and then running the test suite to see if the tests can detect the changes, or "kill" the mutations. It is recommended to generate mutants, run the unit tests, check the reports, and write more or improved tests until reaching a quality target where most or all mutants are killed. Different types of common code mutations are discussed such as replacing operators, variables, or removing conditionals. The goal of mutation testing is to help write a test suite that can detect as many small defects as possible in the code.
At this talk we will start from the basics and come shortly to DynamicProxies, generated type-save DynamicObjectAdapterBuilder and more. We will have a deep dive to this pattern group , and I am sure you will like it ;-)
This talk is based on the german book "Dynamic Proxies" written from Dr. Heinz Kabutz and me.
Dokumen tersebut membahas tentang konsep dasar rangkaian listrik, termasuk definisi rangkaian listrik, komponen listrik aktif dan pasif, arus listrik, tegangan, energi, dan daya. Juga membahas analisis rangkaian dan contoh soal latihan terkait konsep-konsep tersebut.
http://www.jug.ch/html/events/2014/javafx_jumpstart.html
JavaFX - nun endlich ist es soweit. Swing ist offiziell seit Java8 im reinen Wartungsmodus, JavaFX ist der Nachfolger und nun endlich Teil des JDK. Also alles deutet auf neue Zeiten in der Desktopentwicklung hin.. ABER..
Wie kann ich mit JavaFX beginnen?
Wie kann ich es mit Swing Projekten kombinieren?
Gibt es Test-Tools?
Wie beginne ich mit der Migration von Swing auf JavaFX?
Diese oder ähnliche Fragen stellen sich zu Beginn der Arbeit mit JavaFX
Wir werden uns den Start mit JavaFX, Werkzeuge wie TestFX und Kombinationen mit CDI und Swing ansehen.
This document discusses strategies that elites can use to maintain their dominance through soft power. It defines elites as the top 1% who control 40% of the world's wealth and benefit most from the existing power structures. The document presents two main micro-level soft power strategies used by elites: 1) Promoting the idea of personal responsibility to suggest that inequality results from individual choices rather than systemic factors, and 2) Perpetuating the illusion that equality of opportunity exists by highlighting examples of individuals who rose from humble beginnings. It argues that elites in the US rely more on "smart soft power" through subtle manipulation of identities and beliefs rather than overt hard power, allowing them to control society with less repression.
N.Chandrashekar has over 16 years of experience in supply chain management, procurement, inventory control, and logistics. He is currently a Senior Stores Officer at Opto Circuits India Limited in Visakhapatnam, where he is responsible for vendor management, inventory management, and logistics management. He seeks to utilize his strengths in these areas for a reputed organization.
Warum empfehle ich meinen Kunden das Spring Framework? Michael Plöd
In den letzten Jahren wurde vermehrt die Diskussion JEE 6 vs. Spring geführt, wobei immer öfter die Irrelevanz des Spring Frameworks heraufbeschworen wurde. Im Rahmen der Session möchte ich - abseits jeglicher Polemik - in einer ganzheitlichen Betrachtung schildern, warum ich meinen Kunden noch immer zum Einsatz von Spring rate.
OSMC 2010 | Java Monitoring und Troubleshooting by Rainer JungNETWAYS
Ein großer Teil der Geschäftslogik von Unternehmen ist heute in Java-Software abgebildet. Dennoch werden Java-Anwendungen nur allzu häufig als Black Box betrieben und die Analyse von Störungen sehr schnell an Entwicklungsabteilungen delegiert. Diesen steht jedoch in der Regel keine für eine Ursachenanalyse ausreichende Informationsbasis zur Verfügung, so dass Operations und Entwicklung sich auf eine langwierige und schmerzhafte Suche machen.
Dabei bietet die Java-Plattform durchaus interessante Möglichkeiten der Überwachung, die eine schnelle Eingrenzung der Wurzelursache erleichtern, aber leider noch zu wenig bekannt sind und kaum genutzt werden. Im Vortrag werden zunächst einige Grundlagen hierfür vorgestellt, insbesondere JMX. Am Beispiel von Apache Tomcat vertiefen wir, welche für das Monitoring sehr spannenden Parameter dort zur Verfügung stehen, aber auch welche Probleme dieser Ansatz mit sich bringt.
Ein kurzer Ausflug in die Analyse von Java-Thread Dumps schließt den Vortrag ab. Thread Dumps sind der wichtigste – das Monitoring ergänzende – Ansatz für das Troubleshooting von Java-Anwendungen, insbesondere wenn es um Performance-Probleme in verteilten Landschaften geht. Nicht zu vergessen: diese Methode kann auch in Produktion verwendet werden.
Ein Blick in die Kristallkugel mit dem Ziel spannende und relevante Online-Trends für das Jahr 2003 hervorzusagen. Auf der Liste sind:
- JSP 2.0
- XHTML 2
- Platform for Privacy Preferences
- Watermarking
- C#
- Multimedia Home Platform
- Semantic Web
- WLAN
- XSL-FO
- SVG
The article "JavaFX goes Open Source" was published in the German Java Magazin in May 2013 and discussed JavaFX on iOS and Android with their implementations.
The outlook from May 2013 comes true and showed an architecture diagram, how mobile applications could be created with OpenJFX & OpenJDK by the Java developer community using e.g. RoboVM for iOS.
JPA – Der Persistenz-Standard in der Java EE und SEhwilming
Die Abbildung relationaler Strukturen einer Datenbank auf die objekt‐orientierte Programmiersprache Java bringt einige Herausforderungen mit sich, bekannt als object-relational impedance mismatch. In Java ermöglicht JDBC zwar die Interaktion mir einer relationalen Datenbank aber nicht die Abbildung der Daten auf Objekte. Die bekannten Produkte wie Hibernate oder EclipseLink widmen sich diesem Problem bereits seit Jahren. Mit JPA hat der Java Community Process einen Standard für Java EE und SE definiert, der ein einheitliches API bietet, welches von den Anbietern unterstützt wird. Der Vortrag zeigt was JPA bietet und welche Vorteile der Standard für die Anwendungsentwicklung mit sich bringt.
Testgetriebene Entwicklung mit Jasmine und Karma hat sich mittlerweile schon als defacto-Standard etabliert. Routinen ohne Abhängigkeiten lassen sich damit ohne Probleme testen. Die Schwierigkeiten beginnen jedoch schon, wenn es um die Auflösung von Abhängigkeiten geht. In diesem Vortrag werden verschiedene Strategien und Werkzeuge vorgestellt, mit denen Abhängigkeiten zu Objekten und Funktionen oder zum Server abgedeckt werden können. Aber nicht nur Abhängigkeiten stellen Schwierigkeiten bei der testgetriebenen Entwicklung dar, auch der Umgang mit Fixtures ist bei der testgetriebenen Entwicklung mit JavaScript relevant. Abgerundet wird dieser Vortrag mit einigen Best Practices für die testgetriebenen Entwicklung mit JavaScript.
In diesem Webcast bekommen Sie Tipps und Hilfen auf dem Weg zu einer aufgeräumten Java Landschaft, mit der Sie Kosten und Risiken minimieren. Unsere Lizenzierungs- und Java-Experten sprechen dafür u. a. über diese Fragen:
* Wann ist Java "frei"? Und wann nicht?
* Wie Sie Java Installationen entdecken: Scanning-Tools und Inventarisierungslösungen
* Was steckt hinter Java, JDK und JRE? ... Mal genau erklärt
* Welche Open JDKs gibt es? Vor- und Nachteile, Supportmöglichkeiten
* Was wird morgen? Lifecycle Management, Release-Cadence-Wechsel
* Welche Oracle Lizenz-Metriken werden wann angewandt? Prozessor Core Metrik und NUP richtig zählen, Preislisten
* Geht es auch "ohne"?
* Welche Applikationen basieren auf Java?
* Wem gehört mein Java? Spezialfragen im Umfeld von Virtualisierung und Cloud
* Wie lassen sich Kosten sparen? Kostenminimierungsansätze
Die Aufzeichnung finden Sie hier: https://youtu.be/abVeIGmxYB0
DWX 2017 - Alternativen zu Visual-Studio-Testtools: Wann lohnt es sich auch m...Marc Müller
Mittlerweile haben sich im VS-Umfeld immer mehr Nicht-MSTest-Testframeworks etabliert. Im Vortrag wollen wir auf mögliche Alternativen zu MSTest und Coded UI eingehen (z. B. Selenium, Ranorex, Protractor, …). Es geht dabei um Vor-/Nachteile, sinnvolle Szenarien und wie man es geschickt in die TFS-Werkzeugwelt integriert. Das Ziel ist dabei, das Beste aus beiden Welten zu bekommen
JUnit5 Custom TestEngines intro - version 2020-06Sven Ruppert
JUnit5 has been out for some time now, but what are the hidden pearls you can find inside the new Junit Platform? This session explores the possibilities, from @Test over custom extensions up to your own TestEngine. The presentation shows you how to manage a full-stack test in different flavours, based on the JUnit5 possibilities. The main focus is on the development of a custom TestEngine to support project-specific needs. After this, you’ll have all the bits and bytes you need for starting your journey with JUnit5.
Hidden pearls for High-Performance-PersistenceSven Ruppert
Small UseCases with a significant amount of data for internal company usage, most developers had this in their career, already. However, no Ops Team, no Kubernetes, no Cluster is available as part of the solution.
In this talk, I will show a few tech stacks that are helping to deal with persistent data without dealing with the classic horizontal scaling tech monsters like Kubernetes, Hadoop and many more.
Sit down, relax and enjoy the journey through a bunch of lightning-fast persistence alternatives for pure java devs.
Vaadin Flow - How to start - a short intro for Java DevsSven Ruppert
Do you want to write a web application with Core Java? Then you are exactly right here. With Core Java and Vaadin Flow, we will develop a web application from the ground up in this session. We will only use Java, HTML and CSS will not be used during programming. The result, however, will be a web-based application based on web-components that meets the latest standards.
Functional Reactive With Core Java - Voxxed MelbourneSven Ruppert
There are a lot of reactive frameworks in the field, some with functional languages for the JVM. But Java9 give you both. But how you could combine this and use this without adding the next big framework to your project? We will have a Core Java journey to explore a lot of nice possibilities based on the the JDK.
Functional Reactive with Core Java - Workshop - SlidesSven Ruppert
The theme of this workshop is to learn the latest Java features, with an emphasis on picking up a couple of paradigms along the way - namely Functional Reactive Programming and how this fits in with the latest Java releases.
There are a lot of reactive frameworks in the field, some with functional languages for the JVM. But Java9 give you both. But how you could combine this and use this without adding the next big framework to your project? We will have a Core Java journey to explore a lot of nice possibilities based on the the JDK.
From Mess To Masterpiece - JFokus 2017Sven Ruppert
How a migration to MicroServices could change the team, architecture and coding culture. What you could you do and how you could transform a "Jurassic Park" into a lightweight environment. In this talk we will explore the strategy, techniques, pattern and tools I used to transform a team and the architecture that was grown over 15yrs. This will be a mix of pattern, tools and techniques that was able to migrate old systems, used inside insurance and banks. We had to migrate fat systems with a few million lines of code...
CDI (Context Dependency Injection) ermöglicht es dem Entwickler skalierbare und flexible Architekturen aufzubauen die auf einem Java(EE) Server als auch auf dem Desktop laufen. Wie aber sollten DesignPattern aufgebaut werden unter Verwendung von CDI? Was für einen Einfluss hat Java 8 auf die DesignPattern, wie wird es mit der neuen Streams API kombiniert?
Höhepunkt ist die Kombination von klassischen Reflection-Einsatzgebieten wie z.B. dynamic Proxies mit CDI und Cross-Language Injections.
1. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 2/102
Sven Ruppert
has been coding java since 1996
Fellow / Senior Manager
reply Group
Germany - Munich
@SvenRuppert
@SvenRuppert 3/103
2. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 3/102
Twittert bitte ;-)
Zeigt der Community das ihr aktiv seid !!
Fellow / Senior Manager
reply Group
Germany - Munich
@SvenRuppert
@SvenRuppert 4/103
3. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 4/102
Sven Ruppert
speaking java since 1996
Projekte aus den Bereichen:
Wo?
@SvenRuppert
Automobilindustrie
Energieversorgung
Finanzen / Leasingbranche
Luft - Raumfahrt / Satelliten
Behörden / UN / Weltbank
·
·
·
·
·
Europa
Asien - Indien bis Malaysia
·
·
5/103
4. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 5/102
Java 8 - JSR310
java.time - lesson learned by JODA Time
folgendes erwartet uns:
@SvenRuppert
Overview
Core Packages
Naming Conventions
Beispiele
Übungen
·
·
·
·
·
6/103
5. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 6/102
Java 8 - JSR310
Overview
Eigenschaften des JSR310
@SvenRuppert
Clear
Fluent
Immuntable
Extensible
·
·
·
·
7/103
6. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 7/102
Java 8 - JSR310
Overview - Clear
Die Eigenschaften sind intuitiver (Meinung von Oracle)
Beispiel: Wenn ein Parameter mit null übergeben wird, wird eine NullPointerException geworfen.
Ob das im Detail so ist (intuitiver), muss jeder für sich selbst entscheiden.
Viel aus dem Projekt JODA Time gelernt.
@SvenRuppert 8/103
7. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 8/102
Java 8 - JSR310
Overview - Fluent
Es wird eine fluent API angeboten.
Die meisten Methoden erlauben weder ein null als Übergabeparameter, noch geben sie null als Ergebnis
zurück.
(siehe Oracle)
@SvenRuppert
LocalDate today = LocalDate.now();
LocalDate payday = today.with(TemporalAdjuster.lastDayOfMonth()).minusDays(2);
JAVA
9/103
8. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 9/102
Java 8 - JSR310
Overview - Immutable
Die meisten Klassen wurden immutable implementiert.
Date-Time API ist thread-save.
Die meisten Methoden beginnen mit of, from, with
Keine Konstruktorparameter, kaum setter
(siehe Oracle)
@SvenRuppert
LocalDate dateOfBirth = LocalDate.of(2012, Month.MAY, 14);
LocalDate firstBirthday = dateOfBirth.plusYears(1);
JAVA
10/103
9. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 10/102
Java 8 - JSR310
Overview - Extensible
Wo immer möglich, kann die API erweitert werden.
z.B. TimeAdjuster,Queries, eigenes CalendarSystem...
@SvenRuppert 11/103
10. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 11/102
Java 8 - JSR310
Core Packages
Core Packages des JSR310
@SvenRuppert
java.time
java.time.chrono
java.time.format
java.time.temporal
java.time.zone
·
·
·
·
·
12/103
11. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 12/102
Java 8 - JSR310
Core Packages - java.time
java.time
Core API zur Darstellung von Datum und Zeit. (ISO-8601)
Immutable, thread-safe
date, time date/time kombiniert, Zeitzonen, Dauer, Clocks, ..
@SvenRuppert 13/103
12. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 13/102
Java 8 - JSR310
Core Packages - java.time.chrono
java.time.chrono
Alle anderen Calendar-Systeme als ISO-8601
nur von Interesse wenn man eigene Calendar-Systeme entwicklen möchte
@SvenRuppert 14/103
13. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 14/102
Java 8 - JSR310
Core Packages - java.time.format
java.time.format
Formatieren und parsen der Datums- und Zeitangaben
@SvenRuppert 15/103
14. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 15/102
Java 8 - JSR310
Core Packages - java.time.temporal
java.time.temporal
Extended API, für Frameworkentwickler
Ermöglicht die programatische Interoperation zwischen den Basisklassen
@SvenRuppert 16/103
15. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 16/102
Java 8 - JSR310
Core Packages - java.time.zone
java.time.zone
Support für Zeitzonen
wichtigste Klassen: ZonedDateTime, ZoneId, ZoneOffset
@SvenRuppert 17/103
16. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 17/102
Java 8 - JSR310
Naming - Conventions
@SvenRuppert
of - erzeugen von Instanzen
from - erzeugen von Instanzen basierend auf Eingangsinstanz
parse - erzeugen von Instanzen basierend auf Strings
format - erzeugen von Strings basierend auf Pattern
get - Std Getter Methode
is - Queries auf den Objektzustand
with - erzeugt Kopie basierend auf Attributänderung
plus - erzeugt Kopie basierend auf Attributänderung
minus - erzeugt Kopie basierend auf Attributänderung
to - konvertieren in die Instanz der Zielklasse
at - konvertieren in die Instanz der Zielklasse
·
·
·
·
·
·
·
·
·
·
·
18/103
24. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 25/102
Java 8 - JSR310
Beispiele
ZoneId and ZoneOffset:
@SvenRuppert
LocalDateTime dt = LocalDateTime.now();
System.out.println("dt = " + dt);
final ZoneId zoneId = ZoneId.systemDefault();
final ZonedDateTime zonedDateTimeLocal = dt.atZone(zoneId);
System.out.println("zonedDateTimeLocal = " + zonedDateTimeLocal);
//Australia/Darwin +09:30
final ZoneId zoneIdAU = ZoneId.of("Australia/Darwin");
final ZonedDateTime zonedDateTimeAU = dt.atZone(zoneIdAU);
System.out.println("zonedDateTimeAU = " + zonedDateTimeAU);
final ZoneOffset offset = zonedDateTimeAU.getOffset();
System.out.println("offset = " + offset);
/*
dt = 2014-03-31T10:58:43.098
zonedDateTimeLocal = 2014-03-31T10:58:43.098+02:00[Europe/Berlin]
zonedDateTimeAU = 2014-03-31T10:58:43.098+09:30[Australia/Darwin]
offset = +09:30
*/
JAVA
26/103
25. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 26/102
Java 8 - JSR310
Beispiele
OffsetDate / OffsetDateTime:
@SvenRuppert
LocalDateTime date = LocalDateTime.of(2014, Month.APRIL, 20, 19, 30);
ZoneOffset offset = ZoneOffset.of("-02:00");
OffsetDateTime dateOffset = OffsetDateTime.of(date, offset);
OffsetDateTime lastThursday =
dateOffset.with(TemporalAdjusters.lastInMonth(DayOfWeek.THURSDAY));
System.out.printf("The last Thursday in April 2014 is the %sth.%n",
lastThursday.getDayOfMonth());
/*
The last Thursday in April 2014 is the 24th.
*/
JAVA
27/103
26. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 27/102
Java 8 - JSR310
Beispiele
Instant:
@SvenRuppert
final DateTimeFormatter format = DateTimeFormatter.ofPattern("dd.MM.yyyy hh:mm a");
final ZonedDateTime zonedDayTimeNow = ZonedDateTime.now();
final String out = zonedDayTimeNow.format(format);
System.out.println("now = " + out);
/*
now = 31.03.2014 01:05 PM
*/
JAVA
28/103
27. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 28/102
Java 8 - JSR310
Beispiele
Parsing / Formatting:
@SvenRuppert
final DateTimeFormatter format = DateTimeFormatter.ofPattern("dd.MM.yyyy hh:mm a");
final ZonedDateTime zonedDayTimeNow = ZonedDateTime.now();
final String out = zonedDayTimeNow.format(format);
System.out.println("now = " + out);
final LocalDate localDate = LocalDate.parse(out, format);
System.out.println("localDate = " + localDate);
/*
now = 31.03.2014 01:05 PM
*/
JAVA
29/103
28. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 29/102
Java 8 - JSR310
Beispiele
ChronoFields / IsoFields:
@SvenRuppert
import static java.time.temporal.ChronoField.CLOCK_HOUR_OF_DAY;
import static java.time.temporal.ChronoField.DAY_OF_WEEK;
final LocalDate now = LocalDate.now();
System.out.println("LocalDate-CLOCK_HOUR_OF_DAY = " + now.isSupported(CLOCK_HOUR_OF_DAY));
System.out.println("LocalDate-DAY_OF_WEEK = " + now.isSupported(DAY_OF_WEEK));
final LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("localDateTime-CLOCK_HOUR_OF_DAY = " + localDateTime.isSupported(CLOCK_HOUR_OF_DAY));
System.out.println("localDateTime-DAY_OF_WEEK = " + localDateTime.isSupported(DAY_OF_WEEK));
final int i = now.get(IsoFields.QUARTER_OF_YEAR);
System.out.println("QUARTER_OF_YEAR = " + i);
/*
LocalDate-CLOCK_HOUR_OF_DAY = false
LocalDate-DAY_OF_WEEK = true
localDateTime-CLOCK_HOUR_OF_DAY = true
localDateTime-DAY_OF_WEEK = true
QUARTER_OF_YEAR = 1
*/
JAVA
30/103
29. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 30/102
Java 8 - JSR310
Beispiele
TemporalAdjuster 1 / 2:
@SvenRuppert
LocalDate date = LocalDate.of(2014, Month.APRIL, 3);
DayOfWeek dotw = date.getDayOfWeek();
System.out.printf("%s is on a %s%n", date, dotw);
System.out.printf("first day of Month: %s%n",
date.with(TemporalAdjusters.firstDayOfMonth()));
final LocalDate d1 = date.with(new MyTemporalAdjuster());
System.out.println("d1 = " + d1);
final LocalDate dateSa = LocalDate.of(2014, Month.APRIL, 5);
System.out.println("d2 = " + dateSa.with(new MyTemporalAdjuster()));
/*
2014-04-03 is on a THURSDAY
first day of Month: 2014-04-01
d1 = 2014-04-03
d2 = 2014-04-07
*/
JAVA
31/103
30. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 31/102
Java 8 - JSR310
Beispiele
TemporalAdjuster 2 / 2:
@SvenRuppert
public static class MyTemporalAdjuster implements TemporalAdjuster {
@Override
public Temporal adjustInto(Temporal temporal) {
final LocalDate localDate = LocalDate.from(temporal);
final DayOfWeek dayOfWeek = localDate.getDayOfWeek();
if (dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY) {
final TemporalAdjuster next = TemporalAdjusters.next(DayOfWeek.MONDAY);
return temporal.with(next);
} else {
return temporal.with(localDate);
}
}
}
/*
2014-04-03 is on a THURSDAY
first day of Month: 2014-04-01
d1 = 2014-04-03
d2 = 2014-04-07
*/
JAVA
32/103
31. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 32/102
Java 8 - JSR310
Beispiele
TemporalQueries 1 / 3:
@SvenRuppert
TemporalQuery<TemporalUnit> query = TemporalQueries.precision();
System.out.printf("LocalDate precision is %s%n",
LocalDate.now().query(query));
System.out.printf("LocalDateTime precision is %s%n",
LocalDateTime.now().query(query));
System.out.printf("Year precision is %s%n",
Year.now().query(query));
System.out.printf("YearMonth precision is %s%n",
YearMonth.now().query(query));
System.out.printf("Instant precision is %s%n",
Instant.now().query(query));
/*
LocalDate precision is Days
LocalDateTime precision is Nanos
Year precision is Years
YearMonth precision is Months
Instant precision is Nanos
*/
JAVA
33/103
32. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 33/102
Java 8 - JSR310
Beispiele
TemporalQueries 2 / 3:
@SvenRuppert
final Boolean isApril6Mon = of(2014, APRIL, 6).query(new MyTemporalQuery());
final Boolean isApril7Mon = of(2014, APRIL, 7).query(new MyTemporalQuery());
System.out.println("isApril6Mon = " + isApril6Mon);
System.out.println("isApril7Mon = " + isApril7Mon);
public static class MyTemporalQuery implements TemporalQuery<Boolean>{
@Override
public Boolean queryFrom(TemporalAccessor temporal) {
final int i = temporal.get(ChronoField.DAY_OF_WEEK);
if (MONDAY.getValue() == i) return Boolean.TRUE;
else return Boolean.FALSE;
}
}
/*
isApril6Mon = false
isApril7Mon = true
*/
JAVA
34/103
33. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 34/102
Java 8 - JSR310
Beispiele
TemporalQueries 3 / 3:
@SvenRuppert
final TemporalQuery<Boolean> temporalQuery = v -> {
final int i = v.get(ChronoField.DAY_OF_WEEK);
if (MONDAY.getValue() == i) return Boolean.TRUE;
else return Boolean.FALSE;
};
final Boolean isApril6Mon = of(2014, APRIL, 6).query(temporalQuery);
final Boolean isApril7Mon = of(2014, APRIL, 7).query(temporalQuery);
System.out.println("isApril6Mon = " + isApril6Mon);
System.out.println("isApril7Mon = " + isApril7Mon);
/*
isApril6Mon = false
isApril7Mon = true
*/
JAVA
35/103
34. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 35/102
Java 8 - JSR310
Beispiele
Period / Duration 1 / 2:
@SvenRuppert
final Instant t1 = Instant.now();
final Instant t2 = t1.plusSeconds(10);
System.out.println("t1 = " + t1);
System.out.println("t2 = " + t2);
final Duration between = Duration.between(t1, t2);
final long seconds = between.getSeconds();
System.out.println("seconds = " + seconds);
/*
t1 = 2014-04-01T09:05:57.854Z
t2 = 2014-04-01T09:06:07.854Z
seconds = 10
*/
JAVA
36/103
35. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 36/102
Java 8 - JSR310
Beispiele
Period / Duration 2 / 2:
@SvenRuppert
System.out.println(ChronoUnit.SECONDS.between(t2, t1));
final LocalDate d1 = LocalDate.of(2010, 10, 10);
final LocalDate d2 = LocalDate.of(2011, 10, 10);
final Period period = Period.between(d1, d2);
System.out.println("period = " + period);
System.out.println("total years " + period.getYears());
System.out.println("total month " + period.getMonths());
System.out.println("total days " + period.getDays());
System.out.println("total month " + period.toTotalMonths());
/*
-10
period = P1Y
total years 1
total month 0
total days 0
total month 12
*/
JAVA
37/103
36. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 37/102
Java 8 - JSR310
Beispiele
Clock:
@SvenRuppert
final Clock clock = Clock.systemDefaultZone();
final ZoneId zone = clock.getZone();
System.out.println("zone = " + zone);
final Instant instant = clock.instant();
System.out.println("instant = " + instant);
final Clock fixed = Clock.fixed(instant, zone);
System.out.println("fixed.instant() = " + fixed.instant());
System.out.println("fixed.instant() = " + fixed.instant());
System.out.println("fixed.instant() = " + fixed.instant());
/*
zone = Europe/Berlin
instant = 2014-04-01T11:22:01.757Z
fixed.instant() = 2014-04-01T11:22:01.757Z
fixed.instant() = 2014-04-01T11:22:01.757Z
fixed.instant() = 2014-04-01T11:22:01.757Z
fixed.instant() = 2014-04-01T11:22:01.757Z
*/
JAVA
38/103
38. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 39/102
Java 8 - JSR310
Beispiele
Legacy Code :
@SvenRuppert
Instant inst = new Date().toInstant();
Date newDate = Date.from(inst);
final Instant now = Calendar.getInstance().toInstant();
ZonedDateTime zdt = ZonedDateTime.ofInstant(now, ZoneId.systemDefault());
JAVA
40/103
39. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 40/102
Java 8 - JSR310
Overview
Class or Enum Year Month Day Hours Minutes Seconds* Zone Offset Zone ID toString Output
Instant 2013-08-20T15:16:26.355Z
LocalDate 2013-08-20
LocalDateTime 2013-08-20T08:16:26.937
ZonedDateTime 2013-08-21T00:16:26.941+09:00[Asia/Tokyo]
LocalTime 08:16:26.943
MonthDay --08-20
Year 2013
YearMonth 2013-08
Month AUGUST
OffsetDateTime 2013-08-20T08:16:26.954-07:00
OffsetTime 08:16:26.957-07:00
Duration ** ** ** PT20H (20 hours)
Period *** *** P10D (10 days)
@SvenRuppert 41/103
40. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 41/102
Java 8 - JSR310
Aufgabe
Select the ServiceCenter
Ein User gibt eine Nachricht in ein SupportSystem ein. Basierend auf seiner Zeitzone und Urzeit/Datum
soll der ServiceCenter ausgewählt werden der gerade aktiv ist.
ServiceCenter sind: Berlin, New York, Sydney,Kuala Lumpur.
Geschäftszeiten: 0900 - 1600
Ist gerade keines aktiv, soll das nächst öffnende ausgesucht werden.
@SvenRuppert 42/103
41. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 42/102
Java 8 - Streams
Overview
folgendes erwartet uns:
@SvenRuppert
Data in - Data out
Core Methods
Streams v Threads v Serial
JavaFX Beispiel
Streams Pattern Beispiele
·
·
·
·
·
43/103
42. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 43/102
Java 8 - Streams
Data in - Data out
folgendes erwartet uns:
@SvenRuppert
Was sind Streams
Daten - Quellen
Daten - Senken
Fazit
·
·
·
·
44/103
43. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 44/102
Data in - Data out- Was sind Streams
Streams in Java8 sind:
@SvenRuppert
Sind keine Datenstruktur
Für den Einsatz von Lambdas konzipiert worden
Bieten keinen wahlfreien Zugriff per Index oder ähnliches
Sind lazy organisiert
Sind parallel, wenn gewünscht
Sind ungebunden, da sie nicht wie Collections initial befüllt werden
·
·
·
·
·
·
45/103
44. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 45/102
Data in - Data out- Daten - Quellen
Streams können statisch oder dynamisch befüllt werden.
Statisch:
Dynamisch:
@SvenRuppert
Stream.of(val1,val2,val3…) , Stream.of(array) und list.stream(). JAVA
final Stream<Pair> stream = Stream.<Pair>builder().add(new Pair()).build();
Stream.generate(() -> {
final Pair p = new Pair();
p.id = random.nextInt(100);
p.value = "Value + " + p.id;
return p;
})
JAVA
46/103
45. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 46/102
Data in - Data out- Daten - Senken
Ergebnis als Array und als Map
@SvenRuppert
stream.toArray();
stream.collect(Collectors.toList());
stream.collect(Collectors.toSet());
stream.collect(Collectors.groupingBy(..))
JAVA
final List<Pair> generateDemoValues = generateDemoValues();
final Pair[] toArray = generateDemoValues.stream().toArray(Pair[]::new);
final Map<Integer,List<Pair>> collectedToMap = generateDemoValues.stream()
.collect(Collectors.groupingBy(Pair::getId));
JAVA
47/103
46. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 47/102
Data in - Data out- Fazit
Sehr schön zu sehen ist, dass sich die Streams einfach in bestehenden JavaCode einbinden lassen.
Keine unnötigen Wrapper oder ähnliches sind zu schreiben. Die Integration ist damit mühelos in
Altprojekten genauso möglich wie in neuen Projekten.
Hat man sich an die API ein wenig gewöhnt, fallen einem sehr viele Stellen auf, in denen eine starke
Codereduktion durch den Einsatz von Streams erreicht werden kann.
@SvenRuppert 48/103
47. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 48/102
Data in - Data out- Aufgaben
Erzeuge einen Stream aus 10 Elementen der Klasse Pair.
Konsumiere alle Elemente des Streams. (System.out)
Überführe den Stream in
@SvenRuppert
aus einer Liste
mit einem Builder
mit einem Suplier
·
·
·
eine Liste
ein Array
in eine Map
·
·
·
49/103
49. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 50/102
Core Methods - forEach
Diese Methode ist auch bei Iterable, List, Map und einigen anderen Klassen/Interfaces zu finden, was
erfreulicherweise zu kürzeren sprachlichen Konstrukten führt
@SvenRuppert
public static void main(String[] args) {
final List<Pair> generateDemoValues = new PairListGenerator(){}.generateDemoValues();
//pre JDK8
for (final Pair generateDemoValue : generateDemoValues) {
System.out.println(generateDemoValue);
}
//long version
generateDemoValues.stream().forEach(v -> System.out.println(v) );
//short version
generateDemoValues.stream().forEach(System.out::println);
generateDemoValues.stream().forEachOrdered(System.out::println);
final Consumer<? super Pair> consumer = System.out::println;
generateDemoValues.stream().forEachOrdered(consumer);
}
JAVA
51/103
50. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 51/102
Core Methods - map (1/2)
Die Methode map(lambda) erzeugt einen neuen Stream bestehend aus der Summe aller
Transformationen der Elemente des Quell-Streams. Auch hier wieder ist das Argument ein Lambda. Das
bedeutet, dass der Zielstream bis auf die funktionale Kopplung nichts mit dem Quellstream gemeinsam
haben muss.
@SvenRuppert
private static Stream<DemoElement> getDemoElementStream(List<Pair> generateDemoValues) {
//map from Point to DemoElements
return generateDemoValues.stream().map(v -> {
final String value = v.getValue();
final DemoElement d = new DemoElement();
d.setDatum(new Date());
d.setValue(Base64.getEncoder().encodeToString(value.getBytes()));
return d;
});
}
JAVA
52/103
51. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 52/102
Core Methods - map (2/2)
@SvenRuppert
public static void main(String[] args) {
final List<Pair> generateDemoValues = new PairListGenerator(){}.generateDemoValues();
final Stream<DemoElement> demoElementStream = getDemoElementStream(generateDemoValues);
final Stream<String> stringStream = getDemoElementStream(generateDemoValues)
.map(v -> v.getValue());
final Stream<String> stringStreamShort = getDemoElementStream(generateDemoValues)
.map(DemoElement::getValue);
//map from Point to DemoElements to Strings
final List<String> stringList = generateDemoValues.stream().map(v -> {
final String value = v.getValue();
final DemoElement d = new DemoElement();
d.setDatum(new Date());
d.setValue(Base64.getEncoder().encodeToString(value.getBytes()));
return d;
})
.map(DemoElement::getValue).collect(Collectors.toList());
}
JAVA
53/103
52. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 53/102
Core Methods - filter
Wie die Methode map(lambda), erzeugt die Methode filter(Lambda) ebenfalls einen neuen Stream. Aus
der Menge der Quellelemente werden die für die weiteren Schritte benötigten Elemente herausgefiltert.
@SvenRuppert
public static void main(String[] args) {
final List<Pair> generateDemoValues = new PairListGenerator(){}.generateDemoValues();
final Stream<Pair> filteredPairStream = generateDemoValues.stream().filter(v -> v.getId() % 2 == 0);
}
JAVA
54/103
53. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 54/102
Core Methods - findFirst
Immer wieder gibt es eine Menge von Elementen, deren Reihenfolge nicht definiert, die Anzahl
unbestimmt, aber genau ein Element dieser Menge mit bestimmten Eigenschaften zu entnehmen ist.
Was auf der Datenbank dank SQL kein Problem in den meisten Fällen darstellt, kann auf der imperativen
Seite schon mal zu einem längeren Stück Quelltext führen. Die Methode findFirst() liefert das erste
Element aus dem Stream. Auf den ersten Blick eine triviale Methode, so mehr erfreut man sich beim
zweiten Blick. Der Rückgabewert ist ein Optional im Falle eine leeren Streams ein leeres Optional.
@SvenRuppert
final List<String> demoValues = Arrays.asList("AB", "AAB", "AAAB", "AAAAB", "AAAAAB");
final String value = demoValues
.stream()
.filter(o -> o.contains("AAA"))
.findFirst().orElse("noop ");
System.out.println("value = " + value);
JAVA
55/103
54. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 55/102
Core Methods - reduce
Bei den bisherigen Betrachtungen wurden ausschließlich Transformationen betrachtet, die eine
Abbildung von n auf m darstellten. Die Methode reduce((v1,v2)->) jedoch ermöglicht die Abbildung von n
Elementen auf ein finales Element.
@SvenRuppert
final List<String> demoValues = Arrays.asList("A", "B", "C", "D", "E");
System.out.println(demoValues.stream()
.reduce(String::concat));
System.out.println(demoValues.stream()
.reduce("X_", (v1,v2)->{
System.out.println("v1 -> " + v1);
System.out.println("v2 -> " + v2);
return v1.concat(v2)+"_";
}));
System.out.println(demoValues.parallelStream()
.reduce("X_", (v1,v2)->{
// System.out.println("v1 -> " + v1);
// System.out.println("v2 -> " + v2);
final String result = v1.concat(v2) + "_";
System.out.println("v1 " + v1 + " plus v2_ " + v2 + "_ => " + result);
return result;
}));
JAVA
56/103
55. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 56/102
Core Methods - reduce
v1 -> X_
v2 -> A
v1 -> X_A_
v2 -> B
v1 -> X_A_B_
v2 -> C
v1 -> X_A_B_C_
v2 -> D
v1 -> X_A_B_C_D_
v2 -> E
X_A_B_C_D_E_
@SvenRuppert
System.out.println(demoValues.stream()
.reduce("X_", (v1,v2)->{
System.out.println("v1 -> " + v1);
System.out.println("v2 -> " + v2);
return v1.concat(v2)+"_";
}));
JAVA
57/103
56. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 57/102
Core Methods - reduce
v1 X_ plus v2_ C_ => X_C#
v1 X_ plus v2_ A_ => X_A#
v1 X_ plus v2_ D_ => X_D#
v1 X_ plus v2_ B_ => X_B#
v1 X_ plus v2_ E_ => X_E#
v1 X_A# plus v2_ X_B#_ => X_A#X_B##
v1 X_D# plus v2_ X_E#_ => X_D#X_E##
v1 X_C# plus v2_ X_D#X_E##_ => X_C#X_D#X_E###
v1 X_A#X_B## plus v2_ X_C#X_D#X_E###_ => X_A#X_B##X_C#X_D#X_E####
X_A#X_B##X_C#X_D#X_E####
@SvenRuppert
System.out.println(demoValues.parallelStream()
.reduce("X_", (v1,v2)->{
final String result = v1.concat(v2) + "#";
System.out.println("v1 " + v1 + " plus v2_ " + v2 + "_ => " + result);
return result;
}));
JAVA
58/103
57. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 58/102
Core Methods - limit/skip
Streams können undefiniert lang sein. Das bedeutet, dass im Extremfall ein Stream kein Ende hat. Es ist
also manchmal sinnvoll, Streams nur bis zu einer bestimmten Länge abzuarbeiten, oder nur eine
bestimmte Menge von Ergebnissen zu sammeln, da der Rest nicht mehr für die nachfolgende Logik zu
verwenden ist. Die Methode limit(count) ist genau dafür gedacht.
@SvenRuppert
final List<Integer> demoValues
= Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
//limit the input
System.out.println(demoValues.stream().limit(4).collect(Collectors.toList()));
//limit the result
System.out.println(demoValues
.stream().filter((v) -> v > 4).limit(4).collect(Collectors.toList()));
System.out.println(demoValues
.stream().skip(4).collect(Collectors.toList()));
JAVA
59/103
58. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 59/102
Core Methods - distinct
Aus dem Bereich SQL kennt man den Befehl distinct, um eine Menge von Werten auf jeweils nur ein
Exemplar eines Wertes zu reduzieren. Also das Erzeugen einer unique – Menge. Genau dasselbe erledigt
die Methode distinct().
@SvenRuppert
// example result:
// [77, 79, 81, 95, 43, 10, 53, 48, 74, 68, 60, 86, 83, 24, 57, 28, 8,
// 85, 70, 66, 20, 14, 97, 73, 22, 36, 40, 39, 32, 19, 41, 67, 25, 88]
final Random random = new Random();
System.out.println(
Stream.generate(() -> random.nextInt(100))
.limit(40)
.distinct()
.collect(Collectors.toList())
);
JAVA
60/103
59. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 60/102
Core Methods - min/max
Die Methoden min(Comparator) und max(Comparator) liefern aus der Menge der Werte im Stream das
Minimum, bzw das Maximum.
@SvenRuppert
final List<Integer> demoValues
= Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
//find the maximum
System.out.println(demoValues
.stream().max(Integer::compareTo)
);
//find the BUG ;-)
System.out.println(demoValues
.stream().min((v1, v2) -> Integer.compare(v2, v1))
);
JAVA
61/103
60. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 61/102
Core Methods - allMatch/anyMatch/noneMatch
Die Methoden allMatch(<Predicate>), anyMatch(<Predicate>), none-Match(<Predicate>) liefern ein
boolean zurück. allMatch wenn die definierte Bedingung bei genau allen Elementen zutrifft, anyMatch
wenn einige Elemente der Bedingung entsprechen (mind 2 in diesem Beispiel) noneMatch wenn kein
einziges Element der Bedingung entspricht.
@SvenRuppert
public static final List<Integer> demoValues = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
private static Stream<Integer> getStream() {return demoValues.stream();}
static final Function<Integer, Integer> f = (e) -> {
System.out.println("e = " + e);
return e;
};
public static void main(String[] args) {
// true, some are matching
System.out.println("anyMatch " + getStream().map(f).anyMatch((v) -> v % 2 == 0));
//false, not all are matching
System.out.println("allMatch " + getStream().map(f).allMatch((v) -> v % 2 == 0));
//false, not all are NOT matching
System.out.println("noneMatch " + getStream().map(f).noneMatch((v) -> v % 2 == 0));
//5 matching the filter, 2,4,6,8,10
System.out.println("count " + getStream().map(f).filter((v) -> v % 2 == 0).count());
}
JAVA
62/103
61. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 62/102
Core Methods - parallel / sequenziell
Die beiden letzten Methoden die wir uns hier ansehen werden sind parallel() und sequential(). Die
Methoden die wiederum einen Stream zurückliefern können so explizit in eine serielle oder parallele
Version geschaltet werden.
@SvenRuppert
final List<Integer> demoValues
= Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println(demoValues.stream() //seriell
.map((m1) -> m1)
.parallel()
.map((m2) -> m2)
.sequential() //seriell
.collect(Collectors.toList()));
}
JAVA
63/103
62. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 63/102
Core Methods - Fazit
Schon diese wenigen Basis-Methoden ermöglichen einem nach sehr kurzer Einarbeitung Streams recht
effizient und effektiv einzusetzen. Zur Übung kann ich empfehlen bestehende Quelltexte in Konstrukte
mit Streams umzuformen. Dabei wird sich zeigen, dass mit dieser Transformation eine starke Code-
Reduktion einhergeht. An so mancher Stelle kann man dank der Streams auch Teilaufgaben
parallelisieren, was zu einer höheren Auslastung der vorhandenen modernen CPU-Architekturen führt.
@SvenRuppert 64/103
63. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 64/102
Sven Ruppert
Pause...
may the coffee be with us!
Dauer 5min
64. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 65/102
Java 8 - Streams
Streams v Threads v Serial
Wir werden nun ein Beispiel durchgehen, in dem wir eine Aufgabe einmal klassisch seriell, dann mittels
Threads und zum Schluss mit Streams realisieren. Wie groß sind die Unterschiede in der
Codekomplexität, welche Performanceunterschiede gibt es?
folgendes erwartet uns:
@SvenRuppert
Die Aufgabe
Seriell
Threads
Streams
Fazit
·
·
·
·
·
66/103
65. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 66/102
Streams v Threads v Serial - Die Aufgabe
Beginnen wir mit einem einfachen Interface: Der Worker , in dem zwei Methoden definiert werden die
zur synthetischen Lasterzeugung verwendet werden. Ziel hier ist es, zuerst eine Matrix mit Stützstellen
aufzubauen (generateDemoValueMatrix), die danach mittels Splines interpoliert wird
(generateInterpolatedValues).
Der erste Teil ist die Erzeu-gung einer Wertereihe (DemoValueGenerator) zur Darstellung der
Stützstellen. Die Implementierung wurde als Interface mit default – Methode gewählt, was einer JDK8
Notation entspricht. Die Implementierung selbst erfolgte an der Stelle noch ohne Streams.
Der zweite Teil ist die Berechnung der interpolierten Werte (WorkLoadGenerator), was hier zum einen
der Lasterzeugung dient und zum anderen als Beispiel zum Einbinden von ThirdParty-Code verwendet
wird.
@SvenRuppert 67/103
66. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 67/102
Streams v Threads v Serial - Die Aufgabe / Worker
@SvenRuppert
public interface Worker {
public static final int ANZAHL_KURVEN = 200;
public static final int ANZAHL_MESSWERTE = 10;
public static final int MAX_GENERATED_INT = 100;
public abstract List<List<Integer>> generateDemoValueMatrix();
public abstract List<List<Double>>
generateInterpolatedValues(List<List<Integer>> baseValues);
}
JAVA
68/103
67. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 68/102
Streams v Threads v Serial - Seriell
@SvenRuppert
public class WorkerSerial implements Worker {
@Override
public List<List<Double>>
generateInterpolatedValues(List<List<Integer>> baseValues) {
final WorkLoadGenerator generator = new WorkLoadGenerator();
final List<List<Double>> result = new ArrayList<>();
for (final List<Integer> valueList : baseValues) {
final List<Double> doubleList = generator.generate(valueList);
result.add(doubleList);
}
return result;
}
private DemoValueGenerator valueGenerator = new DemoValueGenerator(){};
public List<List<Integer>> generateDemoValueMatrix() {
final List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < ANZAHL_KURVEN; i++) {
final List<Integer> demoValuesForY
= valueGenerator.generateDemoValuesForY();
result.add(demoValuesForY);
}
return result;
}
}
JAVA
69/103
68. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 69/102
Streams v Threads v Serial - Threads (1/3)
@SvenRuppert
@Override
public List<List<Integer>> generateDemoValueMatrix() {
final List<List<Integer>> result = new ArrayList<>();
final List<Task> taskList = new ArrayList<>();
for(int i = 0; i< ANZAHL_KURVEN; i++){
taskList.add(new Task());
}
for (final Task task : taskList) {
task.run();
}
for (final Task task : taskList) {
try {
task.join();
result.add(task.result);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return result;
}
JAVA
70/103
69. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 70/102
Streams v Threads v Serial - Threads (2/3)
@SvenRuppert
@Override
public List<List<Double>>
generateInterpolatedValues(List<List<Integer>> baseValues) {
final List<List<Double>> result = new ArrayList<>();
final List<TaskInterpolate> taskList = new ArrayList<>();
for (final List<Integer> baseValue : baseValues) {
final TaskInterpolate taskInterpolate = new TaskInterpolate();
taskInterpolate.values.addAll(baseValue);
taskList.add(taskInterpolate);
}
for (final TaskInterpolate task : taskList) {
task.run();
}
for (final TaskInterpolate task : taskList) {
try {
task.join();
result.add(task.result);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return result;
}
JAVA
71/103
70. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 71/102
Streams v Threads v Serial - Threads (3/3)
@SvenRuppert
public static class Task extends Thread {
public List<Integer> result = new ArrayList<>();
private DemoValueGenerator valueGenerator = new DemoValueGenerator(){};
@Override
public void run() {
result.addAll(valueGenerator.generateDemoValuesForY());
}
}
public static class TaskInterpolate extends Thread {
public final List<Integer> values = new ArrayList<>();
public final List<Double> result = new ArrayList<>();
private final WorkLoadGenerator generator = new WorkLoadGenerator();
@Override
public void run() {
result.addAll(generator.generate(values));
}
}
JAVA
72/103
71. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 72/102
Übung..
Lösung mittels Streams
Dauer 15min
72. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 73/102
Streams v Threads v Serial - Streams (Lösung 1/3)
@SvenRuppert
public class WorkerParallelStreams implements Worker{
public List<Integer> generateDemoValuesForY(){
final Random random = new Random();
return Stream
.generate(() -> random.nextInt(MAX_GENERATED_INT))
.limit(ANZAHL_MESSWERTE)
.collect(Collectors.toList());
}
//..
}
JAVA
74/103
73. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 74/102
Streams v Threads v Serial - Streams (Lösung 2/3)
@SvenRuppert
public class WorkerParallelStreams implements Worker{
@Override
public List<List<Integer>> generateDemoValueMatrix(){
return Stream
.generate(this::generateDemoValuesForY)
.limit(ANZAHL_KURVEN)
.collect(Collectors.toList());
}
}
JAVA
75/103
74. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 75/102
Streams v Threads v Serial - Streams (Lösung 3/3)
@SvenRuppert
public class WorkerParallelStreams implements Worker{
@Override
public List<List<Double>> generateInterpolatedValues(List<List<Integer>> baseValueMatrix) {
baseValueMatrix.parallelStream()
.map(v -> {
final WorkLoadGenerator generator
= new WorkLoadGenerator();
return generator.generate(v);
})
.collect(Collectors.toList());
return baseValueMatrix;
}
}
JAVA
76/103
75. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 76/102
Übung..
Lösung mittels Streams und default Methoden
Dauer 5min
76. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 77/102
Ergebnis
Vergleich der Lösungungen
77. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 78/102
Serial v Threads v Streams
78. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 79/102
Streams v Threads v Serial - Fazit
Zusammenfassend kann man sagen, dass die Kombination von Streams und den weiteren neuen
Sprachelementen von dem JDK8 zu einer deutlichen Codereduktion führen können.
Schon einfache Bestandteile können parallelisiert werden, ohne das der Entwickler sich mit den sonst
notwendigen Konstrukten wie z.B. Threads auseinandersetzt.
Es sollte allerdings auch hier beachtet werden, ganz ohne Verständnis für Nebenläufigkeit geht es auch
hier nicht. Nicht zwangsläufig ist eine parallele Implementierung auch die effizienteste Implementierung,
geschweige denn semantisch dieselbe.
@SvenRuppert 80/103
79. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 80/102
Sven Ruppert
Pause...
may the coffee be with us!
Dauer 5min
80. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 81/102
Java 8 - Streams
JavaFX Beispiel
folgendes erwartet uns:
@SvenRuppert
Hole (generiere) die Reihe der Messwerte
Berechne die interpolierten Werte
Erzeuge die graphischen Elemente
Befülle das Line-Chart
Fazit
·
·
·
·
·
82/103
81. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 82/102
JavaFX Beispiel - 1a/5
@SvenRuppert
public List<List<Integer>> generateDemoValueMatrix() {
final List<List<Integer>> resultMatrix = new ArrayList<>();
final Random random = new Random();
for(int anzahlKurven = 0; anzahlKurven <ANZAHL_KURVEN; anzahlKurven++){
final List<Integer> result = new ArrayList<>();
for (int i = 0; i < 10; i++) {
final int nextInt = random.nextInt(100);
result.add(nextInt);
}
resultMatrix.add(result);
}
return resultMatrix;
}
JAVA
83/103
82. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 83/102
JavaFX Beispiel - 1b/5
@SvenRuppert
public List<List<Integer>> generateDemoValueMatrix() {
final List<List<Integer>> result = new ArrayList<>();
for(int anzahlKurven = 0; anzahlKurven <ANZAHL_KURVEN; anzahlKurven++){
final List<Integer> demoValuesForY = generateDemoValuesForY();
result.add(demoValuesForY);
}
return result;
}
public List<Integer> generateDemoValuesForY() {
final Random random = new Random();
final List<Integer> result = new ArrayList<>();
for (int i = 0; i < 10; i++) {
final int nextInt = random.nextInt(100);
result.add(nextInt);
}
return result;
}
JAVA
84/103
83. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 84/102
JavaFX Beispiel - 1c/5
@SvenRuppert
public List<List<Integer>> generateDemoValueMatrix() {
return Stream
.generate(this::generateDemoValuesForY)
.limit(ANZAHL_KURVEN)
.collect(Collectors.toList());
}
public List<Integer> generateDemoValuesForY(){
final Random random = new Random();
return Stream
.generate(() -> {
return random.nextInt(100);
})
.limit(10)
.collect(Collectors.toList());
}
JAVA
85/103
84. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 85/102
JavaFX Beispiel - 1d/5
@SvenRuppert
public List<List<Integer>> generateDemoValueMatrix() {
return Stream
.generate(this::generateDemoValuesForY)
.limit(ANZAHL_KURVEN)
.collect(Collectors.toList());
}
public List<Integer> generateDemoValuesForY(){
final Random random = new Random();
return Stream
.generate(() -> random.nextInt(100))
.limit(10)
.collect(Collectors.toList());
}
JAVA
86/103
85. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 86/102
JavaFX Beispiel - 1e/5
@SvenRuppert
public List<List<Integer>> generateDemoValueMatrix() {
return Stream
.generate(this::generateDemoValuesForY)
.limit(ANZAHL_KURVEN)
.collect(Collectors.toList());
}
public List<Integer> generateDemoValuesForY(){
return new Random()
.ints(0, 100)
.limit(10)
.boxed()
.collect(Collectors.toList());
}
JAVA
87/103
86. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 87/102
JavaFX Beispiel - 1f/5
@SvenRuppert
public List<List<Integer>> generateDemoValueMatrix() {
final Random random = new Random();
return Stream.generate(
() -> Stream.generate(
() -> random.nextInt(100))
.limit(10)
.collect(Collectors.toList())
)
.limit(ANZAHL_KURVEN)
.collect(Collectors.toList());
}
JAVA
88/103
87. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 88/102
JavaFX Beispiel - 1g/5
@SvenRuppert
public List<List<Integer>> generateDemoValueMatrix() {
return Stream.generate(
() -> new Random()
.ints(0, 100)
.limit(10)
.boxed()
.collect(Collectors.toList())
).limit(ANZAHL_KURVEN)
.collect(Collectors.toList());
}
JAVA
public List<List<Integer>> generateDemoValueMatrix() {
return generate(() -> new Random()
.ints(0, 100)
.limit(10).boxed().collect(toList())
).limit(ANZAHL_KURVEN).collect(toList());
}
JAVA
89/103
88. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 89/102
JavaFX Beispiel - 1 Vergleich / 5
@SvenRuppert
public List<List<Integer>> generateDemoValueMatrix() {
final List<List<Integer>> resultMatrix = new ArrayList<>();
final Random random = new Random();
for(int anzahlKurven = 0; anzahlKurven <ANZAHL_KURVEN; anzahlKurven++){
final List<Integer> result = new ArrayList<>();
for (int i = 0; i < 10; i++) {
final int nextInt = random.nextInt(100);
result.add(nextInt);
}
resultMatrix.add(result);
}
return resultMatrix;
}
JAVA
public List<List<Integer>> generateDemoValueMatrix() {
return generate(() -> new Random()
.ints(0, 100)
.limit(10).boxed().collect(toList())
).limit(ANZAHL_KURVEN).collect(toList());
}
JAVA
90/103
89. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 90/102
JavaFX Beispiel - 1/2
@SvenRuppert
private List<List<Double>> getValuesForSeries() {
final List<List<Integer>> demoValueMatrix = generateDemoValueMatrix();
return demoValueMatrix
.parallelStream()
.map(v -> {
final UnivariateFunction interpolateFunction = createInterpolateFunction(v);
//baue Kurve auf
final int anzahlValuesInterpolated = (v.size() - 1) * STEP_SIZE;
return IntStream
.rangeClosed(0, anzahlValuesInterpolated).parallel().boxed()
.map(interpolateFunction::value)
.collect(toList());
})
.collect(toList());
}
JAVA
91/103
90. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 91/102
JavaFX Beispiel - 2/2
@SvenRuppert
private List<XYChart.Series> generateNextSeries() {
final List<XYChart.Series> chartSeries = getValuesForSeries()
.parallelStream()
.map(v -> {
final XYChart.Series nextSeries = new XYChart.Series();
IntStream.range(0,v.size()).forEach((i)->{
final XYChart.Data data = new XYChart.Data(i, v.get(i));
nextSeries.getData().add(data);
});
return nextSeries;
}).collect(toList());
return chartSeries;
}
JAVA
92/103
91. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 92/102
JavaFX Beispiel - Fazit
Paralleles Erzeugen der GUI Elemente hat in diesem Beispiel einen spürbaren SpeedUP!
@SvenRuppert 93/103
92. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 93/102
Java 8 - Streams
Streams Pattern Beispiele
folgendes erwartet uns:
@SvenRuppert
Fibonacci
Matrix
Random
Fazit
·
·
·
·
94/103
93. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 94/102
Streams Pattern Beispiele - Fibonacci
@SvenRuppert
public static void main(String[] args) {
makeFibStream(10).forEachOrdered(System.out::println);
}
public static Stream<Long> makeFibStream() {
return(Stream.generate(new FibonacciSupplier()));
}
public static Stream<Long> makeFibStream(int numFibs) {
return(makeFibStream().limit(numFibs));
}
public static List<Long> makeFibList(int numFibs) {
return(makeFibStream(numFibs).collect(Collectors.toList()));
}
public static class FibonacciSupplier implements Supplier<Long> {
private long previous = 0;
private long current = 1;
@Override
public Long get() {
long next = current + previous;
previous = current;
current = next;
return(previous);
}
}
JAVA
95/103
94. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 95/102
Ad hoc Übung..
Finde die Zahl 66
Dauer 15min :-)
finalList<List<Integer>>matrix=newArrayList<>();
matrix.add(Arrays.asList(1,2,3,4,5,6,7,8,9));
matrix.add(Arrays.asList(1,2,3,4,5,66,7,8,9));//hiereine66
matrix.add(Arrays.asList(1,2,3,4,5,6,7,8,9));
JAVA
95. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 96/102
Streams Pattern Beispiele - Lösung
Finde die Zahl 66
@SvenRuppert
public static void main(String[] args) {
final List<List<Integer>> matrix = new ArrayList<>();
matrix.add(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
matrix.add(Arrays.asList(1,2,3,4,5,66,7,8,9)); //hier eine 66
matrix.add(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
matrix.forEach(System.out::println);
final Integer s = matrix.stream()
.map(l -> l.stream()
.filter(v -> v.equals(66))
.findFirst().orElse(null))
.filter(f -> f != null)
.findFirst().orElse(null);
System.out.println("s = " + s);
}
JAVA
97/103
96. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 97/102
Streams Pattern Beispiele - Random
@SvenRuppert
new Random()
.doubles()
.boxed()
.map((d) -> {
final TemperaturSensorValue v = new TemperaturSensorValue();
v.setDate(new Date());
v.setSensorID("testID");
v.setValue(d);
return v;
})
.limit(1_000_000)
.forEach((t) -> {
try {
repo.create(t);
} catch (ArangoDb4JException e) {
e.printStackTrace();
}
});
JAVA
98/103
97. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 98/102
Streams Pattern Beispiele - Fazit
Bei der Verwendung von Streams stellen sich unter anderem folgende Fragen.
Alles in Allem sind Streams eine sehr effektive Unterstützung bei der täglichen Arbeit mit Java. Gerade
durch den generischen Ansatz ist bei typischen Geschäftsanwendungen schon eine angenehme
Erleichterung zu realisieren. Die Einarbeitung in Streams sollte normalerweise innerhalb von 2-3
Arbeitstagen zu spürbaren Ergebnissen führen.
@SvenRuppert
Ist eine Nebenläufigkeit gewünscht oder nicht? Wenn ja, dann sind Streams mittels Verwendung von
parallelStream() in vielen Fällen ein einfacher und schneller Ansatz.
Soll die Verschachtelung des Kontrollflusses gemindert werden? Hier ist es abhängig von den
Konstrukten innerhalb der Fallunterscheidun-gen selbst. Mit leichten Veränderungen lassen sich
mittels Streams recht oft aussagekräftigere Konstrukte aufbauen, die auf lange Sicht zu einer besseren
Wartbarkeit führen. Ob sich das bei Alt-Projekten immer lohnt muss also im Einzelfall endschieden
werden.
Sind mathematische Funktionen abzubilden? Hier kann man in vielen Fällen mittels Streams schneller
zum Erfolg kommen, ohne gleich Scala oder andere funktionale Sprachen in das Projekt zu integrieren.
·
·
·
99/103
98. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 99/102
Java 8 Streams
eBook - 4,99.- Amazon
99. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 100/102
Book about Reflection
my book with Dr, Heinz Kabutz
.. soon
CDI und Reflection... ein teuflisches Paar
z.B. ...dynamic static proxies... ;-)
100. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 101/102
IoT für Java-Entwickler
..soon
101. 20.10.2015 Java 8 ready for the future - JUG
http://localhost:63342/java-courses/doc/java8-kickstart.html#1 102/102
<Thank You!>
g+ www.google.com/+SvenRuppert
twitter @SvenRuppert
www www.rapidpm.org
github github.com/svenruppert