SlideShare a Scribd company logo
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.1
Java 8:
Create The Future
Александр Белокрылов
@gigabel
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.3
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.4
Включайтесь!
 Вступайте в OTN – http://oracle.com/otn
 JUG Belarus – http://www.belarusjug.org/
 Adopt a JSR – http://adoptajsr.java.net
 Канал Java на YouTube – http://youtube.com/java
 Читайте бесплатный журнал – http://www.oracle.com/javamagazine
 Follow Java Twitter – http://twitter.com/java
Будьте частью сообщества
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.5
Java 8
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.6
Java 8
 Лямбда выражения
 Групповые операции
 Nashorn – движок Javascript
 Аннотации типов
 Новый API даты и времени
 Сompact profiles
 New UI controls, Modena, 3D – Java FX
http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.7
Java 8
 Лямбда выражения
 Групповые операции
 Аннотации типов
 Новый API даты и времени
 Сompact profiles
 New UI controls, Modena, 3D – Java FX
http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.8
Type annotations
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.9
Анотации в Java
@Stateless @LocalBean public class GalleryFacade {
@EJB private GalleryEAO galleryEAO;
@TransactionAttribute(SUPPORTS)
public Gallery findById(Long id) { ... }
@TransactionAttribute(REQUIRED)
public void create(String name) { … }
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.10
Аннотации в Java
 Появились в Java 5
 Built-in
@Override
@Deprecated
@SupressWarning
 Custom
 Широко используются
JavaEE
Test harnesses
@
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.11
Аннотации в Java 7 и раньше
Declarations only
– Class
– Method
– Field
– Parameter
– Variable
@A public class Test {
@B private int a = 0;
@C public void m(@D Object o) {
@E int a = 1;
...
}
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.12
Custom annotations
 Определить
 Использовать в коде
 Использовать в runtime
– Reflection
 Использовать в compile-time
– Annotation processor
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.13
Аннотации в Java 8
 Типы могут быть проаннотированы
повторяющиеся аннотации
@
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.14
JSR 308: Annotations on Java Types (1)
 method receivers
public int size() @Readonly { ... }
 generic type arguments
Map<@NonNull String, @NonEmpty List<@Readonly Document>> files;
 arrays
Document[][@Readonly] docs2 = new Document[2] [@Readonly 12];
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.15
JSR 308: Annotations on Java Types (2)
 typecasts
myString = (@NonNull String)myObject;
 type tests
boolean isNonNull = myString instanceof @NonNull String;
 object creation
new @NonEmpty @Readonly List(myNonEmptyStringSet)
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.16
JSR 308: Annotations on Java Types (3)
 type parameter bounds
<T extends @A Object, U extends @C Cloneable>
 class inheritance
– class UnmodifiableList implements @Readonly List<@Readonly T> { ... }
 throws clauses
– void monitorTemperature() throws @Critical TemperatureException { ... }
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.17
Аннотации в Java 8
 Используются в типах
 Анализ во время компиляции
И что?
 Огромная работа по верификации во время компиляции
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.18
JSR 305: Annotations for Software Defect
Detection
 Nullness
 Check return value
 Taint
 Concurrency
 Internationalization
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.19
Checkers framework. Type checkers.
 Nullness
 IGJ (Immutability Generics Java)
 Lock
 Property file
 Units
 Typestate
@
http://types.cs.washington.edu/checker-framework/
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.20
IGJ (Immutability Generics Java) checkers
 @Immutable
 @Mutable
 @ReadOnly
 @Assignable
 @AssignFields
javac -processor org.checkerframework.checker.igj.IGJChecker IGJExample.java
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.21
Новый API даты и
времени
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.22
LocalDate
 Год-Месяц-День (2014-04-16)
 Хранит даты: День рождения, начальная/конечная дата, праздник
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.23
LocalDate
Пример
LocalDate current = LocalDate.now();
LocalDate programmerDay = LocalDate.of(2014,
Month.SEPTEMBER, 13);
if (current.isEqual(programmerDay))
System.out.println("Congratulate friends");
String str = current.toString(); // 2014.05.17
boolean leap = current.isLeapYear(); // false
int daysInMonth = current.lengthOfMonth(); // 30
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.24
LocalDate
 Методы для увеличения, уменьшения и установки даты
 Immutable
Изменяем дату
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.25
LocalDate
Изменяем дату
LocalDate date = LocalDate.now();
date = date.plusMonths(2).minusDays(15);
date = date.withDayOfMonth(9);
date = date.with(Month.MAY);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.26
LocalDate
Изменяем дату по-человечески
date = date.with(TemporalAdjuster.firstDayOfNextMonth());
date = date.with(firstDayOfNextMonth());
date = date.with(next(DayOfWeek.MONDAY));
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.27
LocalTime
Пример
LocalTime current = LocalTime.now();
LocalTime time = LocalTime.of(12, 35);
String str = time.toString(); //12:35
time = time.plusHours(1).minusMinutes(45).withSecond(30);
// 12:35:30
time = time.truncatedTo(ChronoUnit.MINUTES); // 12:50
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.28
LocalDateTime
Пример
LocalDateTime current = LocalDateTime.now();
LocalDateTime arrival =
LocalDateTime.of(2014, Month.MAY, 16, 21, 00);
LocalDateTime departure =
arrival.plusDays(1).plusHours(21).minusMinutes(35);
String str = departure.toString(); //2014-05-18T17:25
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.29
Instant
миллисекунды с 01.01.1970
Instant timeStamp1 = Instant.now();
Instant timeStamp2 = Instant.now();
if (timeStamp1.isAfter(timeStamp2)) ... ;
Instant timeStamp3 = timeStamp2.plusSeconds(10);
эквивалент java.util.Date
24 октября 2014 года, 09:03:34 UTC, EPOCH = 14 14 14 14 14
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.30
Часовые пояса
 Часовые пояса определяются политическими мотивами
 Правила часовых поясов меняются
 http://www.iana.org/time-zones
TimeZones
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.31
ZonedDateTime
аналог java.util.GregorianCalendar
ZoneId moscow = ZoneId.of("Europe/Moscow");
ZoneId berlin = ZoneId.of("Europe/Berlin");
LocalDateTime dateTime =
LocalDateTime.of(2014, Month.MAY, 30, 7, 30);
ZonedDateTime moscowDateTime =
ZonedDateTime.of(dateTime, moscow);
//2014-05-04T07:30+04:00[Europe/Moscow]
ZonedDateTime berlinTime =
moscowDateTime.withZoneSameInstant(berlin);
//2014-05-04T05:30+02:00[Europe/Berlin]
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.32
Интервалы
Время
Duration myTalkDuration = Duration.ofMinutes(45);
myTalkDuration = myTalkDuration.plusMinutes(5);
startTalk = LocalDateTime.of(2014, Month.May, 17, 11, 00);
endTalk = startTalk.plus(myTalkDuration);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.33
Интервалы
Дата
startArmy = LocalDate.of(2014, Month.May, 30);
Period armyPeriod = Period.ofYears(1);
endArmy = startArmy.plus(armyPeriod);
currentDate = LocalDate.of(2014, Month.NOVEMBER, 29);
Period tillDembel = Period.between(currentDate, endArmy);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.34
Пользуйтесь на здоровье!
New Date & Time API Java 8
LocalDate 2014-04-16
LocalTime 12:35:30
LocalDateTime 2014-04-16T22:55
ZonedDateTime 2014-05-04T07:30+04:00[Europe/Moscow]
Instant 1397216152942
Duration PT1H10M
Period P4M6D
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.35
Лямбда выражения
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.36
for (Orange o: orangebox) {
if (o.getColor() == GREEN)
o.setColor(ORANGE);
}
http://www.californiaoranges.com/40lb-box-bushel-organic-valencia-oranges.html
Common case
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.37
orangebox.forEach( o → {
if (o.getColor() == GREEN)
o.setColor(ORANGE);
})
http://www.californiaoranges.com/40lb-box-bushel-organic-valencia-oranges.html
Common case with Lambdas
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.38
Collection.forEach()
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.39
interface Collection<T> {
...
default void forEach(Block<T> action) {
for (T t: this)
action.apply(t);
}
}
Default methods
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.40
Маленький шаг для языка –
гигантский скачок для библиотек
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.41
Stream API
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.42
Mary had a little lambda
Whose fleece was white and snow
And everywhere that Mary went
Lambda was sure to go!
Mary had a little Lambda
https://github.com/steveonjava/MaryHadALittleLambda
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.43
Iterating with Lambdas
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.44
Итерации с Лямбдами
Group cells = new Group(IntStream
.range(0, HORIZONTAL_CELLS)
.mapToObj(i-> IntStream
.range(0, VERTICAL_CELLS)
.mapToObj(j -> {
// Logic goes here
return rect;}))
.flatMap(s -> s)
.toArray(Rectangle[]::new));
Stream generation
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.45
Итерации с Лямбдами
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.46
Iterating with Lambdas
Stream.iterate(tail, lamb -> new SpriteView.Lamb(lamb))
.skip(1).limit(7)
.forEach(s.getAnimals()::add);
Stream iterate()
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.47
•Стрим из коллекции
Collection.stream();
•Стрим объектов
Stream.of(bananas, oranges, apples);
•Числовой дипапзон
IntStream.range(0, 100);
•Итеративность
Stream.iterate(tail, lamb -> new Lamb(lamb));
Итерации с Лямбдами
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.48
Фильтруем Стрим с Лямбдами
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.49
Фильтруем Стрим с Лямбдами
public void visit(Shepherd s) {
s.getAnimals().stream().filter(a -> a.getNumber() % 4 == 1)
.forEach(a -> a.setColor(null));
s.getAnimals().stream().filter(a -> a.getNumber() % 4 == 2)
.forEach(a -> a.setColor(Color.YELLOW));
s.getAnimals().stream().filter(a -> a.getNumber() % 4 == 3)
.forEach(a -> a.setColor(Color.CYAN));
s.getAnimals().stream().filter(a -> a.getNumber() % 4 == 0)
.forEach(a -> a.setColor(Color.GREEN));
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.50
Фильтруем Стрим с Лямбдами
public static Predicate<SpriteView> checkIfLambIs(Integer number) {
return lamb -> lamb.getNumber() % 4 == number;}
@Override
public void visit(Shepherd s) {
s.getAnimals().stream().filter(checkIfLambIs(1))
.forEach(a -> a.setColor(null));
s.getAnimals().stream().filter(checkIfLambIs(2))
.forEach(a -> a.setColor(Color.YELLOW));
s.getAnimals().stream().filter(checkIfLambIs(3))
.forEach(a -> a.setColor(Color.CYAN));
s.getAnimals().stream().filter(checkIfLambIs(0))
.forEach(a -> a.setColor(Color.GREEN));}
Predicate
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.51
Фильтруем коллекции с Лямбдами
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.52
Фильтруем коллекции с Лямбдами
static Function<Color, Predicate<SpriteView>> checkIfLambColorIs
= color -> {Predicate<SpriteView> checkIfColorIs =
lamb -> lamb.getColor() == color;
return checkIfColorIs; };
@Override
public void visit(Shepherd s) {
mealsServed.set(mealsServed.get() +
s.getAnimals()
.filtered(checkIfLambColorIs.apply(todayEatableColor))
.size());
s.getAnimals()
.removeIf(checkIfLambColorIs.apply(todayEatableColor)); }
Function
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.53
Фильтруем коллекции с Лямбдами
@Override
public void visit(Shepherd s) {
Function<Color, Predicate<SpriteView>> checkIfLambColorIs =
color -> lamb -> lamb.getColor() ==
color;
mealsServed.set(mealsServed.get() +
s.getAnimals()
.filtered(checkIfLambColorIs.apply(todayEatableColor))
.size());
s.getAnimals()
.removeIf(checkIfLambColorIs.apply(todayEatableColor))}
Function
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.54
•Removes all elements that match the predicate
Collection.removeIf();
•Filtering and replacement
Collection.replaceAll();
•Returns collection filtered by predicate
ObservableCollection.filtered();
Фильтруем коллекции с Лямбдами
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.55
•OpenSource project to demonstrate
Lambda features
•Visual representation of streams, filters,
maps
•Created by Stephen Chin, @steveonjava
Mary had a little Lambda
https://github.com/steveonjava/MaryHadALittleLambda
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.56
Reading
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.57
Reading
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.58
Java SE Embedded 8
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.59
Java SE 8 Embedded Platforms
JDK ARM SE
Linux ARM VFP hard float ABI
JRE SE Embedded Compact
Profile Platforms
Linux x86
Linux ARM soft float
Linux ARM VFP soft float ABI
Linux ARM VFP hard float ABI
Linux Power PC e600
Linux Power PC e500v2
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.60
Java SE 8 Compact Profiles
Profiles standardization
SE Full JRE
Hotspot VM
Lang & Util Base Libraries
Other Base Libraries
Integration Libraries
UI & Toolkits
Optional Components
Hotspot VM
Base Compact1 Classes
SE 8 Compact
Profiles
Compact2 Class libraries
Compact3 Class libraries
1
2
3
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.61
Java SE 8 APIs
java.io
java.lang
java.lang.annotation
java.lang.invoke
java.lang.ref
java.lang.reflect
java.math
java.net
java.nio
java.nio.channels
java.nio.channels.spi
java.nio.charset
java.nio.charset.spi
java.nio.file
java.nio.file.attribute
java.nio.file.spi
java.security
java.security.cert
java.security.interfaces
java.security.spec
java.text
java.text.spi
java.time
java.time.chrono
java.time.format
java.time.temporal
java.time.zone
java.util
java.util.concurrent
java.util.concurrent.atomic
java.util.concurrent.locks
java.util.function
java.util.jar
java.util.logging
java.util.regex
java.util.spi
java.util.stream
java.util.zip
javax.crypto
javax.crypto.interfaces
javax.crypto.spec
javax.net
javax.net.ssl
javax.script
javax.security.auth
javax.security.auth.callback
javax.security.auth.login
javax.security.auth.spi
javax.security.auth.x500
javax.security.cert
java.rmi
java.rmi.activation
java.rmi.dgc
java.rmi.registry
java.rmi.server
java.sql
javax.rmi.ssl
javax.sql
javax.transaction
javax.transaction.xa
javax.xml
javax.xml.datatype
javax.xml.namespace
javax.xml.parsers
javax.xml.stream
javax.xml.stream.events
javax.xml.stream.util
javax.xml.transform
javax.xml.transform.dom
javax.xml.transform.sax
javax.xml.transform.stax
javax.xml.transform.stream
javax.xml.validation
javax.xml.xpath
org.w3c.dom
org.w3c.dom.bootstrap
org.w3c.dom.events
org.w3c.dom.ls
org.xml.sax
org.xml.sax.ext
org.xml.sax.helpers
java.lang.instrument
java.lang.management
java.security.acl
java.util.prefs
javax.annotation.processing
javax.lang.model
javax.lang.model.element
javax.lang.model.type
javax.lang.model.util
javax.management
javax.management.loading
javax.management.modelmbean
javax.management.monitor
javax.management.openmbean
javax.management.relation
javax.management.remote
javax.management.remote.rmi
javax.management.timer
javax.naming
javax.naming.directory
javax.naming.event
javax.naming.ldap
javax.naming.spi
javax.security.auth.kerberos
javax.security.sasl
javax.sql.rowset
javax.sql.rowset.serial
javax.sql.rowset.spi
javax.tools
javax.xml.crypto
javax.xml.crypto.dom
javax.xml.crypto.dsig
javax.xml.crypto.dsig.dom
javax.xml.crypto.dsig.keyinfo
javax.xml.crypto.dsig.spec
org.ietf.jgss
java.applet
java.awt .**(13 packages)
java.beans
java.beans.beancontext
javax.accessibility
javax.activation
javax.activity
javax.annotation
javax.imageio
javax.imageio.event
javax.imageio.metadata
javax.imageio.plugins.bmp
javax.imageio.plugins.jpeg
javax.imageio.spi
javax.imageio.stream
javax.jws
javax.jws.soap
javax.print
javax.print.attribute
javax.print.attribute.standard
javax.print.event
javax.rmi
javax.rmi.CORBA
javax.sound.midi
javax.sound.midi.spi
javax.sound.sampled
javax.sound.sampled.spi
javax.swing.** (18 packages)
javax.xml.bind
javax.xml.bind.annotation
javax.xml.bind.annotation.adapters
javax.xml.bind.attachment
javax.xml.bind.helpers
javax.xml.bind.util
javax.xml.soap
javax.xml.ws
javax.xml.ws.handler
javax.xml.ws.handler.soap
javax.xml.ws.http
javax.xml.ws.soap
javax.xml.ws.spi
javax.xml.ws.spi.http
javax.xml.ws.wsaddressing
org.omg.** (28 packages)
compact1
compact1 compact2
compact2 compact3
compact3
Full Java SE
http://openjdk.java.net/jeps/161
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.62
Java SE 8 Embedded Profiles
Linux x86_32 JRE static footprint comparison
compact1 Profile classes
Compact1
Embedded
JRE
Extensions (fx, nashorn, locales,... )
11Mb
Client or Server Hotspot VM
Full JRE profile classes
Full JRE SE
Embedded
JRE SE
156Mb
Web start
Plugin
Control Panel
Deploy
49Mb
Client and Server Hotspot VM
Full JRE profile classes
Commercial features (JFR)Commercial features (JFR)
Minimal* Hotspot VM
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.63
Java SE 8 Embedded Profiles
Graphics Footprint Savings over traditional SE Embedded
Swing/AWT/Java2D Classes
Hotspot VM
SE Embedded Runtime
Swing/AWT App
SE Embedded Graphics Stack
Minimal Hotspot VM
Compact1 Profile
Embedded Java FX App
FX Embedded Stack
X Server
Desktop/Window/Session Managers
Native Toolkit & X11 Libraries
Linux Kernel + Framebuffer driver
OpenGLES2 Library
Linux Kernel + Framebuffer driver
52MB
21MB
Java FX
graphics
Java FX controls
EGL FB Direct FB
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.64
NetBeans
http://wiki.netbeans.org/JavaSEEmbeddedPlan
http://wiki.netbeans.org/JavaSEEmbeddedHowTo
http://wiki.netbeans.org/CompactProfiles
http://docs.oracle.com/javase/8/embedded/develop
-applications/develop-apps-in-netbeans.htm
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.65
Java SE 8 Embedded Compact Profiles
Process used to create custom Java Embedded 8 Runtimes
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.66
JavaFX 8
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.67
JavaFX 8
New Stylesheet
Caspian vs Modena
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.68
JavaFX 8
 New API for printing
– Currently only supported on desktop
 Any node can be printed
Printing Support
PrinterJob job = PrinterJob.createPrinterJob(printer);
job.getJobSettings().setPageLayout(pageLayout);
job.getJobSettings().setPrintQuality(PrintQuality.HIGH);
job.getJobSettings().setPaperSource(PaperSource.MANUAL);
job.getJobSettings().setCollation(Collation.COLLATED);
if (job.printPage(someRichText))
job.endJob();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.69
JavaFX 8
 DatePicker
 TreeTableView
New Controls
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.70
JavaFX 8
 Gestures
– Swipe
– Scroll
– Rotate
– Zoom
 Touch events and touch points
Touch Support
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.71
JavaFX 8
 Predefined shapes
– Box
– Cylinder
– Sphere
 User-defined shapes
– TriangleMesh, MeshView
 PhongMaterial
 Lighting
 Cameras
3D Support
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.72
Резюме
 Java SE 8
– Lambda выражения, streams и functions
– Type annotations
– Date & Time API
– Новые контролы, стили и поддержка 3D в JavaFX
 NetBeans 8, IDE для Java 8
– Lambda, Embedded
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.73
А что дальше?
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.74
Java SE Roadmap
20152013 2014 2016
JDK 8 (Q1 2014)
• Lambda
• JVM Convergence
• JavaScript Interop
• JavaFX 8
•3D API
•Java SE Embedded support
•Enhanced HTML5 support
7u40
• Java Flight Recorder
• Java Mission Control 5.2
• Java Discovery Protocol
• Native memory tracking
• Deployment Rule Set
JDK 9
• Modularity – Jigsaw
• Interoperability
• Cloud
• Ease of Use
• JavaFX JSR
• Optimizations
NetBeans IDE 7.3
• New hints and refactoring
• Scene Builder Support
NetBeans IDE 8
• JDK 8 support
• Scene Builder 2.0 support
Scene Builder 2.0
• JavaFX 8 support
• Enhanced Java IDE support
NetBeans IDE 9
• JDK 9 support
• Scene Builder 3.0 support
Scene Builder 3.0
• JavaFX 9 support
7u21
• Java Client Security Enhancements
• App Store Packaging tools
JDK 8u20
• Deterministic G1
• Java Mission Control 6.0
• Improved JRE installer
• App bundling
enhancements
JDK 8u40
Scene Builder 1.1
• Linux support
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.75

More Related Content

PDF
Java Profiling Tools
PPT
О траффике. Инна Игонтова, глава маркетинга IG dev
PPT
Эффективное использование MVC при разработке бизнес-приложений для Android
PPTX
Платформа Windows Phone 7: развитие, особенности, разработка, Marketplace
PPTX
Продажа мобильного ПО своими рукам
PDF
Тренды App Store. Анастасия Гамезо
PPTX
Droids.by — Белорусское Андроид Сообщество
PDF
Heather Miller
Java Profiling Tools
О траффике. Инна Игонтова, глава маркетинга IG dev
Эффективное использование MVC при разработке бизнес-приложений для Android
Платформа Windows Phone 7: развитие, особенности, разработка, Marketplace
Продажа мобильного ПО своими рукам
Тренды App Store. Анастасия Гамезо
Droids.by — Белорусское Андроид Сообщество
Heather Miller

Similar to Александр Белокрылов. Java 8: Create The Future (20)

PDF
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
PDF
Nashorn: Novo Motor Javascript no Java SE 8
PDF
2015 Java update and roadmap, JUG sevilla
PPTX
Thinking Beyond ORM in JPA
PDF
JFall 2016: Oracle JET Session
PDF
Oracle JET, with JET Mobile Content
PPT
GlassFish BOF
PDF
Oracle JET: Enterprise-Ready JavaScript Toolkit
PDF
Java EE 7 for WebLogic 12c Developers
PPTX
Java: how to thrive in the changing world
PDF
JavaScript Dependencies, Modules & Browserify
PDF
Java 8
PDF
What's new in Java 8
PPTX
Functional programming with_jdk8-s_ritter
PDF
Java pode ser_hipster
PPTX
Apache Storm and Oracle Event Processing for Real-time Analytics
PDF
"Quantum" Performance Effects
PDF
Imworld.ro
PDF
Tweet4Beer (atualizada): Torneira de Chopp Controlada por Java, JavaFX, IoT ...
ODP
Java code coverage with JCov. Implementation details and use cases.
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Nashorn: Novo Motor Javascript no Java SE 8
2015 Java update and roadmap, JUG sevilla
Thinking Beyond ORM in JPA
JFall 2016: Oracle JET Session
Oracle JET, with JET Mobile Content
GlassFish BOF
Oracle JET: Enterprise-Ready JavaScript Toolkit
Java EE 7 for WebLogic 12c Developers
Java: how to thrive in the changing world
JavaScript Dependencies, Modules & Browserify
Java 8
What's new in Java 8
Functional programming with_jdk8-s_ritter
Java pode ser_hipster
Apache Storm and Oracle Event Processing for Real-time Analytics
"Quantum" Performance Effects
Imworld.ro
Tweet4Beer (atualizada): Torneira de Chopp Controlada por Java, JavaFX, IoT ...
Java code coverage with JCov. Implementation details and use cases.
Ad

More from Volha Banadyseva (20)

PDF
Андрей Светлов. Aiohttp
PDF
Сергей Зефиров
PDF
Eugene Burmako
PPT
Валерий Прытков, декан факультета КСиС, БГУИР
PPTX
Елена Локтева, «Инфопарк»
PPTX
Татьяна Милова, директор института непрерывного образования БГУ
PDF
Trillhaas Goetz. Innovations in Google and Global Digital Trends
PDF
Александр Чекан. 28 правДИвых слайдов о белорусах в интернете
PDF
Мастер-класс Ильи Красинского и Елены Столбовой. Жизнь до и после выхода в store
PDF
Бахрам Исмаилов. Продвижение мобильного приложение - оптимизация в App Store
PDF
Евгений Пальчевский. Что можно узнать из отзывов пользователей в мобильных ма...
PDF
Евгений Невгень. Оптимизация мета-данных приложения для App Store и Google Play
PDF
Евгений Козяк. Tips & Tricks мобильного прототипирования
PDF
Егор Белый. Модели успешной монетизации мобильных приложений
PDF
Станислав Пацкевич. Инструменты аналитики для мобильных платформ
PDF
Артём Азевич. Эффективные подходы к разработке приложений. Как найти своего п...
PDF
Дина Сударева. Развитие игровой команды и ее самоорганизация. Роль менеджера ...
PDF
Юлия Ерина. Augmented Reality Games: становление и развитие
PDF
Александр Дзюба. Знать игрока: плейтест на стадии прототипа и позже
PDF
Светлана Половинкина. О чём говорит игрок: опросы как инструмент принятия биз...
Андрей Светлов. Aiohttp
Сергей Зефиров
Eugene Burmako
Валерий Прытков, декан факультета КСиС, БГУИР
Елена Локтева, «Инфопарк»
Татьяна Милова, директор института непрерывного образования БГУ
Trillhaas Goetz. Innovations in Google and Global Digital Trends
Александр Чекан. 28 правДИвых слайдов о белорусах в интернете
Мастер-класс Ильи Красинского и Елены Столбовой. Жизнь до и после выхода в store
Бахрам Исмаилов. Продвижение мобильного приложение - оптимизация в App Store
Евгений Пальчевский. Что можно узнать из отзывов пользователей в мобильных ма...
Евгений Невгень. Оптимизация мета-данных приложения для App Store и Google Play
Евгений Козяк. Tips & Tricks мобильного прототипирования
Егор Белый. Модели успешной монетизации мобильных приложений
Станислав Пацкевич. Инструменты аналитики для мобильных платформ
Артём Азевич. Эффективные подходы к разработке приложений. Как найти своего п...
Дина Сударева. Развитие игровой команды и ее самоорганизация. Роль менеджера ...
Юлия Ерина. Augmented Reality Games: становление и развитие
Александр Дзюба. Знать игрока: плейтест на стадии прототипа и позже
Светлана Половинкина. О чём говорит игрок: опросы как инструмент принятия биз...
Ad

Recently uploaded (20)

PPTX
ai tools demonstartion for schools and inter college
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
L1 - Introduction to python Backend.pptx
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
Operating system designcfffgfgggggggvggggggggg
ai tools demonstartion for schools and inter college
CHAPTER 2 - PM Management and IT Context
Upgrade and Innovation Strategies for SAP ERP Customers
VVF-Customer-Presentation2025-Ver1.9.pptx
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Internet Downloader Manager (IDM) Crack 6.42 Build 41
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Design an Analysis of Algorithms I-SECS-1021-03
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Reimagine Home Health with the Power of Agentic AI​
Softaken Excel to vCard Converter Software.pdf
Understanding Forklifts - TECH EHS Solution
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
L1 - Introduction to python Backend.pptx
wealthsignaloriginal-com-DS-text-... (1).pdf
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PTS Company Brochure 2025 (1).pdf.......
Navsoft: AI-Powered Business Solutions & Custom Software Development
Operating system designcfffgfgggggggvggggggggg

Александр Белокрылов. Java 8: Create The Future

  • 1. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.1
  • 2. Java 8: Create The Future Александр Белокрылов @gigabel
  • 3. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.3
  • 4. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.4 Включайтесь!  Вступайте в OTN – http://oracle.com/otn  JUG Belarus – http://www.belarusjug.org/  Adopt a JSR – http://adoptajsr.java.net  Канал Java на YouTube – http://youtube.com/java  Читайте бесплатный журнал – http://www.oracle.com/javamagazine  Follow Java Twitter – http://twitter.com/java Будьте частью сообщества
  • 5. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.5 Java 8
  • 6. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.6 Java 8  Лямбда выражения  Групповые операции  Nashorn – движок Javascript  Аннотации типов  Новый API даты и времени  Сompact profiles  New UI controls, Modena, 3D – Java FX http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html
  • 7. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.7 Java 8  Лямбда выражения  Групповые операции  Аннотации типов  Новый API даты и времени  Сompact profiles  New UI controls, Modena, 3D – Java FX http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html
  • 8. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.8 Type annotations
  • 9. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.9 Анотации в Java @Stateless @LocalBean public class GalleryFacade { @EJB private GalleryEAO galleryEAO; @TransactionAttribute(SUPPORTS) public Gallery findById(Long id) { ... } @TransactionAttribute(REQUIRED) public void create(String name) { … }
  • 10. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.10 Аннотации в Java  Появились в Java 5  Built-in @Override @Deprecated @SupressWarning  Custom  Широко используются JavaEE Test harnesses @
  • 11. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.11 Аннотации в Java 7 и раньше Declarations only – Class – Method – Field – Parameter – Variable @A public class Test { @B private int a = 0; @C public void m(@D Object o) { @E int a = 1; ... } }
  • 12. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.12 Custom annotations  Определить  Использовать в коде  Использовать в runtime – Reflection  Использовать в compile-time – Annotation processor
  • 13. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.13 Аннотации в Java 8  Типы могут быть проаннотированы повторяющиеся аннотации @
  • 14. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.14 JSR 308: Annotations on Java Types (1)  method receivers public int size() @Readonly { ... }  generic type arguments Map<@NonNull String, @NonEmpty List<@Readonly Document>> files;  arrays Document[][@Readonly] docs2 = new Document[2] [@Readonly 12];
  • 15. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.15 JSR 308: Annotations on Java Types (2)  typecasts myString = (@NonNull String)myObject;  type tests boolean isNonNull = myString instanceof @NonNull String;  object creation new @NonEmpty @Readonly List(myNonEmptyStringSet)
  • 16. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.16 JSR 308: Annotations on Java Types (3)  type parameter bounds <T extends @A Object, U extends @C Cloneable>  class inheritance – class UnmodifiableList implements @Readonly List<@Readonly T> { ... }  throws clauses – void monitorTemperature() throws @Critical TemperatureException { ... }
  • 17. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.17 Аннотации в Java 8  Используются в типах  Анализ во время компиляции И что?  Огромная работа по верификации во время компиляции
  • 18. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.18 JSR 305: Annotations for Software Defect Detection  Nullness  Check return value  Taint  Concurrency  Internationalization
  • 19. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.19 Checkers framework. Type checkers.  Nullness  IGJ (Immutability Generics Java)  Lock  Property file  Units  Typestate @ http://types.cs.washington.edu/checker-framework/
  • 20. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.20 IGJ (Immutability Generics Java) checkers  @Immutable  @Mutable  @ReadOnly  @Assignable  @AssignFields javac -processor org.checkerframework.checker.igj.IGJChecker IGJExample.java
  • 21. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.21 Новый API даты и времени
  • 22. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.22 LocalDate  Год-Месяц-День (2014-04-16)  Хранит даты: День рождения, начальная/конечная дата, праздник
  • 23. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.23 LocalDate Пример LocalDate current = LocalDate.now(); LocalDate programmerDay = LocalDate.of(2014, Month.SEPTEMBER, 13); if (current.isEqual(programmerDay)) System.out.println("Congratulate friends"); String str = current.toString(); // 2014.05.17 boolean leap = current.isLeapYear(); // false int daysInMonth = current.lengthOfMonth(); // 30
  • 24. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.24 LocalDate  Методы для увеличения, уменьшения и установки даты  Immutable Изменяем дату
  • 25. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.25 LocalDate Изменяем дату LocalDate date = LocalDate.now(); date = date.plusMonths(2).minusDays(15); date = date.withDayOfMonth(9); date = date.with(Month.MAY);
  • 26. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.26 LocalDate Изменяем дату по-человечески date = date.with(TemporalAdjuster.firstDayOfNextMonth()); date = date.with(firstDayOfNextMonth()); date = date.with(next(DayOfWeek.MONDAY));
  • 27. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.27 LocalTime Пример LocalTime current = LocalTime.now(); LocalTime time = LocalTime.of(12, 35); String str = time.toString(); //12:35 time = time.plusHours(1).minusMinutes(45).withSecond(30); // 12:35:30 time = time.truncatedTo(ChronoUnit.MINUTES); // 12:50
  • 28. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.28 LocalDateTime Пример LocalDateTime current = LocalDateTime.now(); LocalDateTime arrival = LocalDateTime.of(2014, Month.MAY, 16, 21, 00); LocalDateTime departure = arrival.plusDays(1).plusHours(21).minusMinutes(35); String str = departure.toString(); //2014-05-18T17:25
  • 29. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.29 Instant миллисекунды с 01.01.1970 Instant timeStamp1 = Instant.now(); Instant timeStamp2 = Instant.now(); if (timeStamp1.isAfter(timeStamp2)) ... ; Instant timeStamp3 = timeStamp2.plusSeconds(10); эквивалент java.util.Date 24 октября 2014 года, 09:03:34 UTC, EPOCH = 14 14 14 14 14
  • 30. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.30 Часовые пояса  Часовые пояса определяются политическими мотивами  Правила часовых поясов меняются  http://www.iana.org/time-zones TimeZones
  • 31. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.31 ZonedDateTime аналог java.util.GregorianCalendar ZoneId moscow = ZoneId.of("Europe/Moscow"); ZoneId berlin = ZoneId.of("Europe/Berlin"); LocalDateTime dateTime = LocalDateTime.of(2014, Month.MAY, 30, 7, 30); ZonedDateTime moscowDateTime = ZonedDateTime.of(dateTime, moscow); //2014-05-04T07:30+04:00[Europe/Moscow] ZonedDateTime berlinTime = moscowDateTime.withZoneSameInstant(berlin); //2014-05-04T05:30+02:00[Europe/Berlin]
  • 32. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.32 Интервалы Время Duration myTalkDuration = Duration.ofMinutes(45); myTalkDuration = myTalkDuration.plusMinutes(5); startTalk = LocalDateTime.of(2014, Month.May, 17, 11, 00); endTalk = startTalk.plus(myTalkDuration);
  • 33. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.33 Интервалы Дата startArmy = LocalDate.of(2014, Month.May, 30); Period armyPeriod = Period.ofYears(1); endArmy = startArmy.plus(armyPeriod); currentDate = LocalDate.of(2014, Month.NOVEMBER, 29); Period tillDembel = Period.between(currentDate, endArmy);
  • 34. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.34 Пользуйтесь на здоровье! New Date & Time API Java 8 LocalDate 2014-04-16 LocalTime 12:35:30 LocalDateTime 2014-04-16T22:55 ZonedDateTime 2014-05-04T07:30+04:00[Europe/Moscow] Instant 1397216152942 Duration PT1H10M Period P4M6D
  • 35. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.35 Лямбда выражения
  • 36. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.36 for (Orange o: orangebox) { if (o.getColor() == GREEN) o.setColor(ORANGE); } http://www.californiaoranges.com/40lb-box-bushel-organic-valencia-oranges.html Common case
  • 37. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.37 orangebox.forEach( o → { if (o.getColor() == GREEN) o.setColor(ORANGE); }) http://www.californiaoranges.com/40lb-box-bushel-organic-valencia-oranges.html Common case with Lambdas
  • 38. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.38 Collection.forEach()
  • 39. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.39 interface Collection<T> { ... default void forEach(Block<T> action) { for (T t: this) action.apply(t); } } Default methods
  • 40. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.40 Маленький шаг для языка – гигантский скачок для библиотек
  • 41. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.41 Stream API
  • 42. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.42 Mary had a little lambda Whose fleece was white and snow And everywhere that Mary went Lambda was sure to go! Mary had a little Lambda https://github.com/steveonjava/MaryHadALittleLambda
  • 43. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.43 Iterating with Lambdas
  • 44. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.44 Итерации с Лямбдами Group cells = new Group(IntStream .range(0, HORIZONTAL_CELLS) .mapToObj(i-> IntStream .range(0, VERTICAL_CELLS) .mapToObj(j -> { // Logic goes here return rect;})) .flatMap(s -> s) .toArray(Rectangle[]::new)); Stream generation
  • 45. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.45 Итерации с Лямбдами
  • 46. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.46 Iterating with Lambdas Stream.iterate(tail, lamb -> new SpriteView.Lamb(lamb)) .skip(1).limit(7) .forEach(s.getAnimals()::add); Stream iterate()
  • 47. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.47 •Стрим из коллекции Collection.stream(); •Стрим объектов Stream.of(bananas, oranges, apples); •Числовой дипапзон IntStream.range(0, 100); •Итеративность Stream.iterate(tail, lamb -> new Lamb(lamb)); Итерации с Лямбдами
  • 48. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.48 Фильтруем Стрим с Лямбдами
  • 49. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.49 Фильтруем Стрим с Лямбдами public void visit(Shepherd s) { s.getAnimals().stream().filter(a -> a.getNumber() % 4 == 1) .forEach(a -> a.setColor(null)); s.getAnimals().stream().filter(a -> a.getNumber() % 4 == 2) .forEach(a -> a.setColor(Color.YELLOW)); s.getAnimals().stream().filter(a -> a.getNumber() % 4 == 3) .forEach(a -> a.setColor(Color.CYAN)); s.getAnimals().stream().filter(a -> a.getNumber() % 4 == 0) .forEach(a -> a.setColor(Color.GREEN)); }
  • 50. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.50 Фильтруем Стрим с Лямбдами public static Predicate<SpriteView> checkIfLambIs(Integer number) { return lamb -> lamb.getNumber() % 4 == number;} @Override public void visit(Shepherd s) { s.getAnimals().stream().filter(checkIfLambIs(1)) .forEach(a -> a.setColor(null)); s.getAnimals().stream().filter(checkIfLambIs(2)) .forEach(a -> a.setColor(Color.YELLOW)); s.getAnimals().stream().filter(checkIfLambIs(3)) .forEach(a -> a.setColor(Color.CYAN)); s.getAnimals().stream().filter(checkIfLambIs(0)) .forEach(a -> a.setColor(Color.GREEN));} Predicate
  • 51. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.51 Фильтруем коллекции с Лямбдами
  • 52. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.52 Фильтруем коллекции с Лямбдами static Function<Color, Predicate<SpriteView>> checkIfLambColorIs = color -> {Predicate<SpriteView> checkIfColorIs = lamb -> lamb.getColor() == color; return checkIfColorIs; }; @Override public void visit(Shepherd s) { mealsServed.set(mealsServed.get() + s.getAnimals() .filtered(checkIfLambColorIs.apply(todayEatableColor)) .size()); s.getAnimals() .removeIf(checkIfLambColorIs.apply(todayEatableColor)); } Function
  • 53. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.53 Фильтруем коллекции с Лямбдами @Override public void visit(Shepherd s) { Function<Color, Predicate<SpriteView>> checkIfLambColorIs = color -> lamb -> lamb.getColor() == color; mealsServed.set(mealsServed.get() + s.getAnimals() .filtered(checkIfLambColorIs.apply(todayEatableColor)) .size()); s.getAnimals() .removeIf(checkIfLambColorIs.apply(todayEatableColor))} Function
  • 54. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.54 •Removes all elements that match the predicate Collection.removeIf(); •Filtering and replacement Collection.replaceAll(); •Returns collection filtered by predicate ObservableCollection.filtered(); Фильтруем коллекции с Лямбдами
  • 55. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.55 •OpenSource project to demonstrate Lambda features •Visual representation of streams, filters, maps •Created by Stephen Chin, @steveonjava Mary had a little Lambda https://github.com/steveonjava/MaryHadALittleLambda
  • 56. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.56 Reading
  • 57. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.57 Reading
  • 58. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.58 Java SE Embedded 8
  • 59. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.59 Java SE 8 Embedded Platforms JDK ARM SE Linux ARM VFP hard float ABI JRE SE Embedded Compact Profile Platforms Linux x86 Linux ARM soft float Linux ARM VFP soft float ABI Linux ARM VFP hard float ABI Linux Power PC e600 Linux Power PC e500v2
  • 60. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.60 Java SE 8 Compact Profiles Profiles standardization SE Full JRE Hotspot VM Lang & Util Base Libraries Other Base Libraries Integration Libraries UI & Toolkits Optional Components Hotspot VM Base Compact1 Classes SE 8 Compact Profiles Compact2 Class libraries Compact3 Class libraries 1 2 3
  • 61. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.61 Java SE 8 APIs java.io java.lang java.lang.annotation java.lang.invoke java.lang.ref java.lang.reflect java.math java.net java.nio java.nio.channels java.nio.channels.spi java.nio.charset java.nio.charset.spi java.nio.file java.nio.file.attribute java.nio.file.spi java.security java.security.cert java.security.interfaces java.security.spec java.text java.text.spi java.time java.time.chrono java.time.format java.time.temporal java.time.zone java.util java.util.concurrent java.util.concurrent.atomic java.util.concurrent.locks java.util.function java.util.jar java.util.logging java.util.regex java.util.spi java.util.stream java.util.zip javax.crypto javax.crypto.interfaces javax.crypto.spec javax.net javax.net.ssl javax.script javax.security.auth javax.security.auth.callback javax.security.auth.login javax.security.auth.spi javax.security.auth.x500 javax.security.cert java.rmi java.rmi.activation java.rmi.dgc java.rmi.registry java.rmi.server java.sql javax.rmi.ssl javax.sql javax.transaction javax.transaction.xa javax.xml javax.xml.datatype javax.xml.namespace javax.xml.parsers javax.xml.stream javax.xml.stream.events javax.xml.stream.util javax.xml.transform javax.xml.transform.dom javax.xml.transform.sax javax.xml.transform.stax javax.xml.transform.stream javax.xml.validation javax.xml.xpath org.w3c.dom org.w3c.dom.bootstrap org.w3c.dom.events org.w3c.dom.ls org.xml.sax org.xml.sax.ext org.xml.sax.helpers java.lang.instrument java.lang.management java.security.acl java.util.prefs javax.annotation.processing javax.lang.model javax.lang.model.element javax.lang.model.type javax.lang.model.util javax.management javax.management.loading javax.management.modelmbean javax.management.monitor javax.management.openmbean javax.management.relation javax.management.remote javax.management.remote.rmi javax.management.timer javax.naming javax.naming.directory javax.naming.event javax.naming.ldap javax.naming.spi javax.security.auth.kerberos javax.security.sasl javax.sql.rowset javax.sql.rowset.serial javax.sql.rowset.spi javax.tools javax.xml.crypto javax.xml.crypto.dom javax.xml.crypto.dsig javax.xml.crypto.dsig.dom javax.xml.crypto.dsig.keyinfo javax.xml.crypto.dsig.spec org.ietf.jgss java.applet java.awt .**(13 packages) java.beans java.beans.beancontext javax.accessibility javax.activation javax.activity javax.annotation javax.imageio javax.imageio.event javax.imageio.metadata javax.imageio.plugins.bmp javax.imageio.plugins.jpeg javax.imageio.spi javax.imageio.stream javax.jws javax.jws.soap javax.print javax.print.attribute javax.print.attribute.standard javax.print.event javax.rmi javax.rmi.CORBA javax.sound.midi javax.sound.midi.spi javax.sound.sampled javax.sound.sampled.spi javax.swing.** (18 packages) javax.xml.bind javax.xml.bind.annotation javax.xml.bind.annotation.adapters javax.xml.bind.attachment javax.xml.bind.helpers javax.xml.bind.util javax.xml.soap javax.xml.ws javax.xml.ws.handler javax.xml.ws.handler.soap javax.xml.ws.http javax.xml.ws.soap javax.xml.ws.spi javax.xml.ws.spi.http javax.xml.ws.wsaddressing org.omg.** (28 packages) compact1 compact1 compact2 compact2 compact3 compact3 Full Java SE http://openjdk.java.net/jeps/161
  • 62. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.62 Java SE 8 Embedded Profiles Linux x86_32 JRE static footprint comparison compact1 Profile classes Compact1 Embedded JRE Extensions (fx, nashorn, locales,... ) 11Mb Client or Server Hotspot VM Full JRE profile classes Full JRE SE Embedded JRE SE 156Mb Web start Plugin Control Panel Deploy 49Mb Client and Server Hotspot VM Full JRE profile classes Commercial features (JFR)Commercial features (JFR) Minimal* Hotspot VM
  • 63. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.63 Java SE 8 Embedded Profiles Graphics Footprint Savings over traditional SE Embedded Swing/AWT/Java2D Classes Hotspot VM SE Embedded Runtime Swing/AWT App SE Embedded Graphics Stack Minimal Hotspot VM Compact1 Profile Embedded Java FX App FX Embedded Stack X Server Desktop/Window/Session Managers Native Toolkit & X11 Libraries Linux Kernel + Framebuffer driver OpenGLES2 Library Linux Kernel + Framebuffer driver 52MB 21MB Java FX graphics Java FX controls EGL FB Direct FB
  • 64. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.64 NetBeans http://wiki.netbeans.org/JavaSEEmbeddedPlan http://wiki.netbeans.org/JavaSEEmbeddedHowTo http://wiki.netbeans.org/CompactProfiles http://docs.oracle.com/javase/8/embedded/develop -applications/develop-apps-in-netbeans.htm
  • 65. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.65 Java SE 8 Embedded Compact Profiles Process used to create custom Java Embedded 8 Runtimes
  • 66. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.66 JavaFX 8
  • 67. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.67 JavaFX 8 New Stylesheet Caspian vs Modena
  • 68. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.68 JavaFX 8  New API for printing – Currently only supported on desktop  Any node can be printed Printing Support PrinterJob job = PrinterJob.createPrinterJob(printer); job.getJobSettings().setPageLayout(pageLayout); job.getJobSettings().setPrintQuality(PrintQuality.HIGH); job.getJobSettings().setPaperSource(PaperSource.MANUAL); job.getJobSettings().setCollation(Collation.COLLATED); if (job.printPage(someRichText)) job.endJob();
  • 69. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.69 JavaFX 8  DatePicker  TreeTableView New Controls
  • 70. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.70 JavaFX 8  Gestures – Swipe – Scroll – Rotate – Zoom  Touch events and touch points Touch Support
  • 71. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.71 JavaFX 8  Predefined shapes – Box – Cylinder – Sphere  User-defined shapes – TriangleMesh, MeshView  PhongMaterial  Lighting  Cameras 3D Support
  • 72. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.72 Резюме  Java SE 8 – Lambda выражения, streams и functions – Type annotations – Date & Time API – Новые контролы, стили и поддержка 3D в JavaFX  NetBeans 8, IDE для Java 8 – Lambda, Embedded
  • 73. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.73 А что дальше?
  • 74. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.74 Java SE Roadmap 20152013 2014 2016 JDK 8 (Q1 2014) • Lambda • JVM Convergence • JavaScript Interop • JavaFX 8 •3D API •Java SE Embedded support •Enhanced HTML5 support 7u40 • Java Flight Recorder • Java Mission Control 5.2 • Java Discovery Protocol • Native memory tracking • Deployment Rule Set JDK 9 • Modularity – Jigsaw • Interoperability • Cloud • Ease of Use • JavaFX JSR • Optimizations NetBeans IDE 7.3 • New hints and refactoring • Scene Builder Support NetBeans IDE 8 • JDK 8 support • Scene Builder 2.0 support Scene Builder 2.0 • JavaFX 8 support • Enhanced Java IDE support NetBeans IDE 9 • JDK 9 support • Scene Builder 3.0 support Scene Builder 3.0 • JavaFX 9 support 7u21 • Java Client Security Enhancements • App Store Packaging tools JDK 8u20 • Deterministic G1 • Java Mission Control 6.0 • Improved JRE installer • App bundling enhancements JDK 8u40 Scene Builder 1.1 • Linux support
  • 75. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.75