SlideShare a Scribd company logo
@Delabassee @JosePaumard#SE84EE
Java EE devs
Java SE 8 for
@Delabassee @JosePaumard#Devoxx #SE84EE
Agenda
Java SE 8 has been released ~1.5 year ago
Java EE 7 Application Servers
- GlassFish, WildFly, Liberty Profile, WebLogic, etc.
@Delabassee @JosePaumard#Devoxx #SE84EE
Agenda
Java SE 8 has been released ~1.5 year ago
Java EE 7 Application Servers
- GlassFish, WildFly, Liberty Profile, WebLogic, etc.
Check some important Java SE 8 new features
for Java EE developers... with patterns!
@Delabassee
@JosePaumard
@JosePaumard
start
The following is intended to outline our general product direction.
It is intended for information purposes only, and may not be
incorporated into any contract. It is not a commitment to deliver
any material, code, or functionality, and should not be relied upon
in making purchasing decisions. The development, release, and
timing of any features or functionality described for Oracle’s
products remains at the sole discretion of Oracle.
@Delabassee @JosePaumard#Devoxx #SE84EE
Questions?
#SE84EE
http://slido.com
Date
@Delabassee @JosePaumard#Devoxx #SE84EE
New Date & Time API
Date & Time API is a new introduction in Java 8
Initiated by Stephen Colebourne, based on Joda Time
Complete replacement of Date & Calendar
@Delabassee @JosePaumard#Devoxx #SE84EE
Date: ZonedTime
Useful for localized times
Set<String> allZonesIds = ZoneId.getAvailableZoneIds() ;
String ukTZ = ZoneId.of("Europe/Paris") ;
@Delabassee @JosePaumard#Devoxx #SE84EE
Date: ZonedTime
Useful for localized times
System.out.println(
ZonedDateTime.of(
1998, Month.JULY.getValue(), 12, // year / month / day
22, 0, 0, 0, // h / mn / s / nanos
ZoneId.of("Europe/Paris"))
); // prints 1998-07-22T22:00-00:01:15[Europe/London]
@Delabassee @JosePaumard#Devoxx #SE84EE
Date: ZonedTime
Useful for localized times
System.out.println(
ZonedDateTime.of(
1998, Month.JULY.getValue(), 12, // year / month / day
22, 0, 0, 0, // h / mn / s / nanos
ZoneId.of("Europe/Paris"))
);
ZonedDateTime nextWorldCup =
currentWorldCup.plus(Period.ofYear(4));
@Delabassee @JosePaumard#Devoxx #SE84EE
Date: ZonedTime
Useful for localized times
System.out.println(
ZonedDateTime.of(
1998, Month.JULY.getValue(), 12, // year / month / day
22, 0, 0, 0, // h / mn / s / nanos
ZoneId.of("Europe/Paris"))
);
ZonedDateTime nextWorldCup =
currentWorldCup.plus(Period.ofYear(4));
ZonedDateTime nexWorldCupJapan=
nextWorldCup.withZoneSameInstant(ZoneId.of("Asia/Tokyo")) ;
@Delabassee @JosePaumard#Devoxx #SE84EE
Date: bridges with java.util.Date
Conversions between j.u.Date and Date & Time
Time time = Time.from(localTime); // API -> legacy
LocalTime localTime = time.toLocalTime(); // legacy -> new API
Date date = Date.from(localDate); // API -> legacy
LocalDate localDate = date.toLocalDate(); // legacy -> new API
TimeStamp time = TimeStamp.from(instant); // API -> legacy
Instant instant = time.toInstant(); // legacy -> new API
Date date = Date.from(instant); // API -> legacy
Instant instant = date.toInstant(); // legacy -> new API
@Delabassee @JosePaumard#Devoxx #SE84EE
Usable in JPA
JPA does not support this Date & Time API (yet)
But with converters, we can still use it
@Entity
public abstract class AbstractPersistent {
@Convert(converter=DateConverter.class)
private Instant instant;
}
@Delabassee @JosePaumard#Devoxx #SE84EE
Usable in JPA
The converter is a classical object
public class DateConverter
implements AttributeConverter<Instant, Date> {
public Date convertToDatabaseColumn(Instant instant) {
return Date.from(instant);
}
public Instant convertToEntityAttribute(Date date) {
return date.toInstant();
}
}
@Delabassee @JosePaumard#Devoxx #SE84EE
Usable in JPA
The converter is a classical object
public class DateFormatConverter
implements AttributeConverter<ZonedDateTime, String> {
public String convertToDatabaseColumn(ZonedDateTime time) {
return DateTimeFormatter.ISO_DATE_TIME.format(time);
}
public ZonedDateTime convertToEntityAttribute(String formated) {
return DateTimeFormatter.ISO_DATE_TIME
.parse(formated, ZonedDateTime::from);
}
}
@Delabassee @JosePaumard#Devoxx #SE84EE
Usable in JPA
With JPA converters we can use the types
from Date & Time API and map in j.u.l.Date or String
@Delabassee @JosePaumard#Devoxx #SE84EE
Usable in JSF
With a Custom JSF Converter
@FacesConverter("instantConverter")
public class TimeConverter implements javax.faces.convert.Converter {
@Override
public Object getAsObject(FacesContext ctx, … , String value) {
return Instant.parse(value);
}
}
@Delabassee @JosePaumard#Devoxx #SE84EE
Usable in JSF
With a Custom JSF Converter...
@Override
public String getAsString(FacesContext ctx, … , Object value) {
DateTimeFormatter formatter =
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
.withLocale(Locale.US)
.withZone(ZoneId.systemDefault());
return formatter.format((TemporalAccessor) value);
}
}
@Delabassee @JosePaumard#Devoxx #SE84EE
Usable in JSF
With a Custom JSF Converter<h:form>
<h:inputText id = "date”
value = "#{order.timestamp}"
size = "20" required="true”
label = "start"
converter = "instantConverter" />
...
@ManagedBean(name="order") @SessionScoped
public class myBean implements Serializable{
Instant timestamp;
…
Annotations
@Delabassee @JosePaumard#Devoxx #SE84EE
Annotations in Java 7
Wrapping annotations
An annotation cannot be applied more than once
@NamedQueries({
@NamedQuery(name=SELECT_ALL, query="..."),
@NamedQuery(name=COUNT_ALL, query="...")
})
public class Customer {
}
@Delabassee @JosePaumard#Devoxx #SE84EE
Annotations in Java 8
Java 8 makes it possible!
@NamedQuery(name=SELECT_ALL, query="..."),
@NamedQuery(name=COUNT_ALL, query="...")
public class Customer {
}
@Delabassee @JosePaumard#Devoxx #SE84EE
Bean Validation
Suppose we want to validate a parameter
public orderdCar order( @CheckCar("VW") Car aCar ) {
...
}
@Delabassee @JosePaumard#Devoxx #SE84EE
Bean Validation
Here is the Bean Validation code for @CheckCar
@Target({PARAMETER})
@Retention(RUNTIME)
@Constraint(validatedBy = CarValidator.class)
public @interface CheckCar {
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String value();
}
@Delabassee @JosePaumard#Devoxx #SE84EE
Bean Validation
And for the validator
public class CarValidator
implements ConstraintValidator<CheckCar, Car> {
private String carBrand;
public void initialize(CheckCar constraintAnnotation) {
this.carBrand = constraintAnnotation.value();
}
public boolean isValid(Car obj, ConstraintValidatorContext ctrCtx) {
if (object == null) return true;
return (!obj.getBrand().toUpperCase().contains(carBrand));
}
}
@Delabassee @JosePaumard#Devoxx #SE84EE
Bean Validation
And the Java 8 trick to make it repeatable
@Target({PARAMETER})
@Retention(RUNTIME)
@Repeatable(CheckCars.class)
@Constraint(validatedBy = CarValidator.class)
public @interface CheckCar {
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String value();
}
@Delabassee @JosePaumard#Devoxx #SE84EE
Bean Validation
And the Java 8 trick to make it repeatable
@Target({PARAMETER})
@Retention(RUNTIME)
public @interface CheckCars {
CheckCar[] value() default{};
}
@Delabassee @JosePaumard#Devoxx #SE84EE
Bean Validation
Suppose we want to validate a parameter
public orderdCar order( @CheckCar("VW") @ChechCar("Audi") Car aCar ) {
...
}
@Delabassee @JosePaumard#Devoxx #SE84EE
Type annotations
Annotations can be now put on types
Example 1: tell that a variable should not be null
private @NonNull List<Person> persons = ... ;
@Delabassee @JosePaumard#Devoxx #SE84EE
Type annotations
Annotations can be now put on types
Example 1: tell that a variable should not be null
Example 2: the content should not be null neither
private @NonNull List<Person> persons = ... ;
private @NonNull List<@NonNull Person> persons = ... ;
String
@Delabassee @JosePaumard#Devoxx #SE84EE
Joining strings
New String joiners are coming to the JDK!
@Delabassee @JosePaumard#Devoxx #SE84EE
Joining strings
StringJoiner class
And it prints:
StringJoiner sj = new StringJoiner(", ") ;
sj.add("one").add("two").add("three") ;
String s = sj.toString() ;
System.out.println(s) ;
> one, two, three
@Delabassee @JosePaumard#Devoxx #SE84EE
Joining strings
StringJoiner with prefix / postfix
And it prints:
StringJoiner sj = new StringJoiner(", ", "{", "}") ;
sj.add("one").add("two").add("three") ;
String s = sj.toString() ;
System.out.println(s) ;
> {one, two, three}
@Delabassee @JosePaumard#Devoxx #SE84EE
Joining strings
Also accessible from the String class
And it prints:
// From the String class, with a vararg
String s = String.join(", ", "one", "two", "three");
System.out.println(s);
> one, two, three
@Delabassee @JosePaumard#Devoxx #SE84EE
Joining strings
And directly from a List
// From a list to a String using the Stream & Collectors API
String s =
listOfStrings.stream()
.collect(Collectors.joining(", "));
System.out.println(s);
> one, two, three
@Delabassee @JosePaumard#Devoxx #SE84EE
Joining strings
And directly from a List
The result is
// From the String class, with a vararg
String s =
listOfStrings.stream()
.collect(Collectors.joining(", ", "{", "}"));
System.out.println(s);
> {one, two, three}
@Delabassee @JosePaumard#Devoxx #SE84EE
Support for Base64 decoding
After a few years…
import java.util.Base64;
String txt = "Modern Times!";
String encoded = Base64.getEncoder().encodeToString(
txt.getBytes(StandardCharsets.UTF_8));
String decoded = new String(Base64.getDecoder().decode(encoded),
StandardCharsets.UTF_8);
Streams
@Delabassee @JosePaumard#Devoxx #SE84EE
What is a Stream?
A new API
A typed interface
A new concept
@Delabassee @JosePaumard#Devoxx #SE84EE
What is a Stream?
A new API
A typed interface
A new concept
Let’s see some code!
@Delabassee @JosePaumard#Devoxx #SE84EE
Readable and efficient patterns
Extract histograms from data
List<Person> people = Arrays.asList();
Map<City, Double> agesByCity =
people.stream()
.filter(p -> p.getAge() > 20)
.collect(
Collectors.groupingBy(
Person::getCity,
Collectors.averagingDouble(Person::getAge)
)
);
@Delabassee @JosePaumard#Devoxx #SE84EE
Readable and efficient patterns
Extract histograms from data
List<Person> people = Arrays.asList();
Map<City, Double> agesByCity =
people.stream()
.filter(p -> p.getAge() > 20)
.collect(
Collectors.groupingBy(
Person::getCity,
Collectors.averagingDouble(Person::getAge)
)
);
@Delabassee @JosePaumard#Devoxx #SE84EE
Readable and efficient patterns
Extract histograms from data
List<Person> people = Arrays.asList();
Map<City, Double> agesByCity =
people.stream()
.filter(p -> p.getAge() > 20)
.collect(
Collectors.groupingBy(
Person::getCity,
Collectors.averagingDouble(Person::getAge)
)
);
@Delabassee @JosePaumard#Devoxx #SE84EE
Readable and efficient patterns
Extract histograms from data
List<Person> people = Arrays.asList();
Map<City, Double> agesByCity =
people.stream()
.filter(p -> p.getAge() > 20)
.collect(
Collectors.groupingBy(
Person::getCity,
Collectors.averagingDouble(Person::getAge)
)
);
@Delabassee @JosePaumard#Devoxx #SE84EE
Readable and efficient patterns
Extract histograms from data
List<Person> people = Arrays.asList();
Map<City, Double> agesByCity =
people.stream()
.filter(p -> p.getAge() > 20)
.collect(
Collectors.groupingBy(
Person::getCity,
Collectors.averagingDouble(Person::getAge)
)
);
@Delabassee @JosePaumard#Devoxx #SE84EE
Readable and efficient patterns
Extract histograms from data
List<Person> people = Arrays.asList();
Map<City, Double> agesByCity =
people.stream()
.filter(p -> p.getAge() > 20)
.collect(
Collectors.groupingBy(
Person::getCity,
Collectors.averagingDouble(Person::getAge)
)
);
@Delabassee @JosePaumard#Devoxx #SE84EE
Building a Stream on a String
Building a Stream on the letters of a String:
String s = "hello";
IntStream stream = s.chars(); // stream on the letters of s
@Delabassee @JosePaumard#Devoxx #SE84EE
Building a Stream on a String
Building a Stream on the letters of a String:
String s = "hello";
IntStream stream = s.chars(); // stream on the letters of s
s.chars() // IntStream
.mapToObj(letter -> (char)letter) // Stream<Character>
.map(Character::toUpperCase)
.forEach(System.out::println); // Prints a Character
> HELLO
@Delabassee @JosePaumard#Devoxx #SE84EE
Build a Stream from a text file
Find the first error line from a log file
// Java 7 : try with resources and use of Paths
Path path = Paths.get("d:", "tmp", "debug.log");
try (Stream<String> stream = Files.lines(path)) {
stream.filter(line -> line.contains("ERROR"))
.findFirst()
.ifPresent(System.out::println);
} catch (IOException ioe) {
// handle the exception
}
@Delabassee @JosePaumard#Devoxx #SE84EE
Build a Stream from a regex
Building a Stream from a regexp
// book is a looooooooong String
Stream<String> words =
Pattern
.compile(" ")
.splitAsStream(book) ;
@Delabassee @JosePaumard#Devoxx #SE84EE
Build a Stream from a regex
Building a Stream from a regexp
More efficient than:
// book is a looooooooong String
Stream<String> words =
Pattern
.compile(" ")
.splitAsStream(book) ;
// book is a looooooooong String
Stream<String> words =
Stream.of(book.split(" "));
@Delabassee @JosePaumard#Devoxx #SE84EE
Flatmap: Files.lines + regex
Splitting a text files into words
Stream<String> streamOfLines = Files.lines(path);
Function<String, Stream<String>> splitter =
line -> Pattern.compile(" ").splitAsStream(line);
long numberOfWords =
streamOfLines.flatMap(splitter)
.map(String::toLowerCase)
.distinct()
.count();
@Delabassee @JosePaumard#Devoxx #SE84EE
Why is it important for Java EE?
Given this JSON file
[
{
"name":"Duke",
"gender":"m",
"phones":[
"home":"650‐123‐4567",
"mobile":"650‐111‐2222"
]
},
{
"name":"Jane", …
]
JsonArray contacts =
Json.createArrayBuilder()
.add(…
@Delabassee @JosePaumard#Devoxx #SE84EE
Why is it important for Java EE?
And some JSON-P magic
Map<String, Long> names =
contacts.getValuesAs(JsonObject.class).stream()
.filter(x -> "f".equals(x.getString("gender")))
.map(x -> (x.getString("name")))
.collect(
Collectors.groupingBy(
Function.identity(),
Collectors.counting()
)
);
@Delabassee @JosePaumard#Devoxx #SE84EE
Why is it important for Java EE?
// Today
JsonArray names =
contacts.getValuesAs(JsonObject.class).stream()
.filter(x -> "f".equals(x.getString("gender")))
.map(x -> (x.getString("name")))
.collect(
Collector.of(
() -> Json.createArrayBuilder(),
(builder, value) -> builder.add(value),
(builder1, builder2) -> builder1.add(builder2),
builder -> builder.build()
)
);
@Delabassee @JosePaumard#Devoxx #SE84EE
Why is it important for Java EE?
// Today
JsonArray names =
contacts.getValuesAs(JsonObject.class).stream()
.filter(x -> "f".equals(x.getString("gender")))
.map(x -> (x.getString("name")))
.collect(
Collector.of(
Json::createArrayBuilder,
JsonArrayBuilder::add,
JsonArrayBuilder::add,
JsonArrayBuilder::build
)
);
@Delabassee @JosePaumard#Devoxx #SE84EE
Why is it important for Java EE?
// Today
JsonArray names =
contacts.getValuesAs(JsonObject.class).stream()
.filter(x -> "f".equals(x.getString("gender")))
.map(x -> (x.getString("name")))
.collect(
Collectors.collectingAndThen(
Collector.of(
Json::createArrayBuilder,
JsonArrayBuilder::add,
JsonArrayBuilder::add
),
JsonArrayBuilder::build
)
);
@Delabassee @JosePaumard#Devoxx #SE84EE
Why is it important for Java EE?
Collect into JSON
Avaiblable through the JsonCollectors factory
// Tomorrow, with JSON-P 1.1
JsonArray names =
contacts.getValuesAs(JsonObject.class).stream()
.filter(x -> "f".equals(x.getString("gender")))
.map(x -> (x.getString("name")))
.collect(
JsonCollectors.toJsonArray()
);
Parallelism
@Delabassee @JosePaumard#Devoxx #SE84EE
A warning on parallelism
All parallel operations (Streams, ConcurrentHashMap)
take place in the common ForkJoinPool
The common ForkJoinPool takes all the
available cores / CPUs
@Delabassee @JosePaumard#Devoxx #SE84EE
A warning on parallelism
All parallel operations (Streams, ConcurrentHashMap)
take place in the common ForkJoinPool
The common ForkJoinPool takes all the
available cores / CPUs
To preserve your Application Server:
System.setProperty(
"java.util.concurrent.ForkJoinPool.common.parallelism", "1") ;
Completable
Future
@Delabassee @JosePaumard#Devoxx #SE84EE
CompletableFuture
New addition to j.u.concurrent
Allow to chain asynchronous tasks
Use case: test the asynchronous calls in the Servlet API,
EJB, JAX-RS, …
@Delabassee @JosePaumard#Devoxx #SE84EE
Creation of an asynchronous task
The Jersey way to create an asynchronous call
@Path("/resource")
public class AsyncResource {
@GET
public void asyncGet(@Suspended final AsyncResponse asyncResponse) {
new Thread(new Runnable() {
public void run() {
String result = longOperation();
asyncResponse.resume(result);
}
}).start();
}
}
@Delabassee @JosePaumard#Devoxx #SE84EE
Creation of an asynchronous task
(let us fix this code with Java 8)
@Path("/resource")
public class AsyncResource {
@GET
public void asyncGet(@Suspended final AsyncResponse asyncResponse) {
executor.submit(() -> {
String result = longOperation();
asyncResponse.resume(result);
});
}
}
@Delabassee @JosePaumard#Devoxx #SE84EE
How to test it?
We want to check if the result object
is passed to the resume() method of the asyncResponse
It is a very basic test, but tricky to write since we are in an
asynchronous world
We have mocks for that!
@Delabassee @JosePaumard#Devoxx #SE84EE
How to test it?
We can inject a mock AsyncResponse, even mock the result
Then verify the correct interaction:
But we need to verify this once the run() method has been
called…
Mockito.verify(mockAsyncResponse).resume(result);
@Delabassee @JosePaumard#Devoxx #SE84EE
How to test it?
This is where CompletionStage come to the rescue!
@Path("/resource")
public class AsyncResource {
@Inject ExecutorService executor;
@GET
public void asyncGet(@Suspended final AsyncResponse asyncResponse) {
executor.submit(() -> {
String result = longOperation();
asyncResponse.resume(result);
});
}
}
@Delabassee @JosePaumard#Devoxx #SE84EE
How to test it?
@Path("/resource")
public class AsyncResource {
@Inject ExecutorService executor;
@GET
public void asyncGet(@Suspended final AsyncResponse asyncResponse) {
executeAsync(asyncResponse);
}
public CompletableFuture<Void> executeAsync(final AsyncResponse asyncResponse) {
return CompletableFuture.runAsync(() -> {
asyncResponse.resume(longOperation());
}, executor);
}
}
@Delabassee @JosePaumard#Devoxx #SE84EE
How to test it?
AsyncResource asyncResource = new AsyncResource();
asyncResource.executeAsync(mockAsyncResponse); // returns the CompletableFuture
.thenRun(() -> { // then execute this Runnable
Mockito.verify(mockAsyncResponse).resume(result);
}
);
@Delabassee @JosePaumard#Devoxx #SE84EE
How to test it?
Be careful of visibility issues
1) It’s better to run this in the same thread
2) Since the mocks are used and checked in this thread,
create them in this thread too
@Delabassee @JosePaumard#Devoxx #SE84EE
How to test it?
So the complete pattern becomes this one
1) First we create our mocks
String result = Mockito.mock(String.class);
AsyncResponse response = Mockito.mock(AsyncResponse.class);
Runnable train = () -> Mockito.doReturn(result).when(response.longOperation());
Runnable verify = () -> Mockito.verify(response).resume(result);
@Delabassee @JosePaumard#Devoxx #SE84EE
How to test it?
So the complete pattern becomes this one
2) Then we create the call & verify
Runnable callAndVerify = () -> {
asyncResource.executeAsync(response).thenRun(verify);
}
@Delabassee @JosePaumard#Devoxx #SE84EE
How to test it?
So the complete pattern becomes this one
3) Then we create the task
ExecutorService executor = Executors.newSingleThreadExecutor();
AsynResource asyncResource = new AsyncResource();
asyncResource.setExecutorService(executor);
CompletableFuture
.runAsync(train, executor) // this trains our mocks
.thenRun(callAndVerify); // this verifies our mocks
@Delabassee @JosePaumard#Devoxx #SE84EE
How to test it?
Since a CompletableFuture is also a Future, we can fail
with a timeout if the test does not complete fast enough
ExecutorService executor = Executors.newSingleThreadExecutor();
AsynResource asyncResource = new AsyncResource();
asyncResource.setExecutorService(executor);
CompletableFuture
.runAsync(train, executor) // this trains our mocks
.thenRun(callAndVerify) // this verifies our mocks
.get(10, TimeUnit.SECONDS);
@Delabassee @JosePaumard#Devoxx #SE84EE
Conclusion
Java 8 is not just about lambdas
There are also many new and very useful patterns
Ready to be used before becoming a lambda ninja!
Not covered:
- Collection framework
- Concurrency, Concurrent hashmap
- JavaScript on the JVM with Nashorn
- Security
@Delabassee @JosePaumard#SE84EE
Thank you!
@Delabassee @JosePaumard#SE84EE

More Related Content

What's hot

Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
José Paumard
 
Java 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven editionJava 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven editionJosé Paumard
 
Going reactive in java
Going reactive in javaGoing reactive in java
Going reactive in java
José Paumard
 
Free your lambdas
Free your lambdasFree your lambdas
Free your lambdas
José Paumard
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
José Paumard
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
CodeOps Technologies LLP
 
Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJava 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava Comparison
José Paumard
 
Autumn collection JavaOne 2014
Autumn collection JavaOne 2014Autumn collection JavaOne 2014
Autumn collection JavaOne 2014
José Paumard
 
httpie
httpiehttpie
An Introduction to Solr
An Introduction to SolrAn Introduction to Solr
An Introduction to Solr
tomhill
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
José Paumard
 
Creating Lazy stream in CSharp
Creating Lazy stream in CSharpCreating Lazy stream in CSharp
Creating Lazy stream in CSharp
Dhaval Dalal
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
Dhaval Dalal
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
Dhaval Dalal
 
React mit TypeScript – eine glückliche Ehe
React mit TypeScript – eine glückliche EheReact mit TypeScript – eine glückliche Ehe
React mit TypeScript – eine glückliche Ehe
inovex GmbH
 
Doctrine ORM with eZ Platform REST API and GraphQL
Doctrine ORM with eZ Platform REST API and GraphQLDoctrine ORM with eZ Platform REST API and GraphQL
Doctrine ORM with eZ Platform REST API and GraphQL
Jani Tarvainen
 
A python web service
A python web serviceA python web service
A python web service
Temian Vlad
 
JAX-RS and CDI Bike the (Reactive) Bridge
JAX-RS and CDI Bike the (Reactive) BridgeJAX-RS and CDI Bike the (Reactive) Bridge
JAX-RS and CDI Bike the (Reactive) Bridge
José Paumard
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
Programming Homework Help
 
Java 8 Stream API (Valdas Zigas)
Java 8 Stream API (Valdas Zigas)Java 8 Stream API (Valdas Zigas)
Java 8 Stream API (Valdas Zigas)
Kaunas Java User Group
 

What's hot (20)

Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
 
Java 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven editionJava 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven edition
 
Going reactive in java
Going reactive in javaGoing reactive in java
Going reactive in java
 
Free your lambdas
Free your lambdasFree your lambdas
Free your lambdas
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
 
Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJava 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava Comparison
 
Autumn collection JavaOne 2014
Autumn collection JavaOne 2014Autumn collection JavaOne 2014
Autumn collection JavaOne 2014
 
httpie
httpiehttpie
httpie
 
An Introduction to Solr
An Introduction to SolrAn Introduction to Solr
An Introduction to Solr
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
 
Creating Lazy stream in CSharp
Creating Lazy stream in CSharpCreating Lazy stream in CSharp
Creating Lazy stream in CSharp
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
 
React mit TypeScript – eine glückliche Ehe
React mit TypeScript – eine glückliche EheReact mit TypeScript – eine glückliche Ehe
React mit TypeScript – eine glückliche Ehe
 
Doctrine ORM with eZ Platform REST API and GraphQL
Doctrine ORM with eZ Platform REST API and GraphQLDoctrine ORM with eZ Platform REST API and GraphQL
Doctrine ORM with eZ Platform REST API and GraphQL
 
A python web service
A python web serviceA python web service
A python web service
 
JAX-RS and CDI Bike the (Reactive) Bridge
JAX-RS and CDI Bike the (Reactive) BridgeJAX-RS and CDI Bike the (Reactive) Bridge
JAX-RS and CDI Bike the (Reactive) Bridge
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Java 8 Stream API (Valdas Zigas)
Java 8 Stream API (Valdas Zigas)Java 8 Stream API (Valdas Zigas)
Java 8 Stream API (Valdas Zigas)
 

Viewers also liked

Linked to ArrayList: the full story
Linked to ArrayList: the full storyLinked to ArrayList: the full story
Linked to ArrayList: the full story
José Paumard
 
ArrayList et LinkedList sont dans un bateau
ArrayList et LinkedList sont dans un bateauArrayList et LinkedList sont dans un bateau
ArrayList et LinkedList sont dans un bateau
José Paumard
 
50 new things we can do with Java 8
50 new things we can do with Java 850 new things we can do with Java 8
50 new things we can do with Java 8
José Paumard
 
50 nouvelles choses que l'on peut faire en Java 8
50 nouvelles choses que l'on peut faire en Java 850 nouvelles choses que l'on peut faire en Java 8
50 nouvelles choses que l'on peut faire en Java 8
José Paumard
 
50 nouvelles choses que l'on peut faire avec Java 8
50 nouvelles choses que l'on peut faire avec Java 850 nouvelles choses que l'on peut faire avec Java 8
50 nouvelles choses que l'on peut faire avec Java 8
José Paumard
 
AWS Innovate: AWS Container Management using Amazon EC2 Container Service an...
AWS Innovate:  AWS Container Management using Amazon EC2 Container Service an...AWS Innovate:  AWS Container Management using Amazon EC2 Container Service an...
AWS Innovate: AWS Container Management using Amazon EC2 Container Service an...
Amazon Web Services Korea
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Haim Michael
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
José Paumard
 
API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8
José Paumard
 
HighLoad++ 2009 In-Memory Data Grids
HighLoad++ 2009 In-Memory Data GridsHighLoad++ 2009 In-Memory Data Grids
HighLoad++ 2009 In-Memory Data Grids
Alexey Kharlamov
 
Phoenix for Rubyists
Phoenix for RubyistsPhoenix for Rubyists
Phoenix for Rubyists
Mike North
 
Hazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMSHazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMS
uzquiano
 
Async Gateway или Разработка системы распределенных вычислений с нуля
Async Gateway или Разработка системы распределенных вычислений с нуляAsync Gateway или Разработка системы распределенных вычислений с нуля
Async Gateway или Разработка системы распределенных вычислений с нуля
Vitebsk Miniq
 
Java 8 Support at the JVM Level
Java 8 Support at the JVM LevelJava 8 Support at the JVM Level
Java 8 Support at the JVM Level
Nikita Lipsky
 
Алексей Николаенков, Devexperts
Алексей Николаенков, DevexpertsАлексей Николаенков, Devexperts
Алексей Николаенков, Devexperts
Nata_Churda
 
Code review at large scale
Code review at large scaleCode review at large scale
Code review at large scale
Mikalai Alimenkou
 
Amazon cloud – готовим вместе
Amazon cloud – готовим вместеAmazon cloud – готовим вместе
Amazon cloud – готовим вместе
Vitebsk Miniq
 
Hazelcast for Terracotta Users
Hazelcast for Terracotta UsersHazelcast for Terracotta Users
Hazelcast for Terracotta Users
Hazelcast
 
ЖК Зорге 9
ЖК Зорге 9ЖК Зорге 9
ЖК Зорге 9
IRCIT.Uspeshnyy
 
Java 8 for Tablets, Pis, and Legos
Java 8 for Tablets, Pis, and LegosJava 8 for Tablets, Pis, and Legos
Java 8 for Tablets, Pis, and Legos
Stephen Chin
 

Viewers also liked (20)

Linked to ArrayList: the full story
Linked to ArrayList: the full storyLinked to ArrayList: the full story
Linked to ArrayList: the full story
 
ArrayList et LinkedList sont dans un bateau
ArrayList et LinkedList sont dans un bateauArrayList et LinkedList sont dans un bateau
ArrayList et LinkedList sont dans un bateau
 
50 new things we can do with Java 8
50 new things we can do with Java 850 new things we can do with Java 8
50 new things we can do with Java 8
 
50 nouvelles choses que l'on peut faire en Java 8
50 nouvelles choses que l'on peut faire en Java 850 nouvelles choses que l'on peut faire en Java 8
50 nouvelles choses que l'on peut faire en Java 8
 
50 nouvelles choses que l'on peut faire avec Java 8
50 nouvelles choses que l'on peut faire avec Java 850 nouvelles choses que l'on peut faire avec Java 8
50 nouvelles choses que l'on peut faire avec Java 8
 
AWS Innovate: AWS Container Management using Amazon EC2 Container Service an...
AWS Innovate:  AWS Container Management using Amazon EC2 Container Service an...AWS Innovate:  AWS Container Management using Amazon EC2 Container Service an...
AWS Innovate: AWS Container Management using Amazon EC2 Container Service an...
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8
 
HighLoad++ 2009 In-Memory Data Grids
HighLoad++ 2009 In-Memory Data GridsHighLoad++ 2009 In-Memory Data Grids
HighLoad++ 2009 In-Memory Data Grids
 
Phoenix for Rubyists
Phoenix for RubyistsPhoenix for Rubyists
Phoenix for Rubyists
 
Hazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMSHazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMS
 
Async Gateway или Разработка системы распределенных вычислений с нуля
Async Gateway или Разработка системы распределенных вычислений с нуляAsync Gateway или Разработка системы распределенных вычислений с нуля
Async Gateway или Разработка системы распределенных вычислений с нуля
 
Java 8 Support at the JVM Level
Java 8 Support at the JVM LevelJava 8 Support at the JVM Level
Java 8 Support at the JVM Level
 
Алексей Николаенков, Devexperts
Алексей Николаенков, DevexpertsАлексей Николаенков, Devexperts
Алексей Николаенков, Devexperts
 
Code review at large scale
Code review at large scaleCode review at large scale
Code review at large scale
 
Amazon cloud – готовим вместе
Amazon cloud – готовим вместеAmazon cloud – готовим вместе
Amazon cloud – готовим вместе
 
Hazelcast for Terracotta Users
Hazelcast for Terracotta UsersHazelcast for Terracotta Users
Hazelcast for Terracotta Users
 
ЖК Зорге 9
ЖК Зорге 9ЖК Зорге 9
ЖК Зорге 9
 
Java 8 for Tablets, Pis, and Legos
Java 8 for Tablets, Pis, and LegosJava 8 for Tablets, Pis, and Legos
Java 8 for Tablets, Pis, and Legos
 

Similar to Java SE 8 for Java EE developers

Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
Guillaume Laforge
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidad
David Gómez García
 
Fifty New Features of Java EE 7 in Fifty Minutes
Fifty New Features of Java EE 7 in Fifty MinutesFifty New Features of Java EE 7 in Fifty Minutes
Fifty New Features of Java EE 7 in Fifty Minutes
Arun Gupta
 
Fifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 MinutesFifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 Minutesglassfish
 
SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)
SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)
SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)
ruthmcdavitt
 
NoSQL Endgame - Java2Days 2020 Virtual
NoSQL Endgame - Java2Days 2020 VirtualNoSQL Endgame - Java2Days 2020 Virtual
NoSQL Endgame - Java2Days 2020 Virtual
Werner Keil
 
Sqladria 2009 SRC
Sqladria 2009 SRCSqladria 2009 SRC
Sqladria 2009 SRC
tepsum
 
05 status-codes
05 status-codes05 status-codes
05 status-codessnopteck
 
Tutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component pluginTutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component plugin
searchbox-com
 
Javaslang @ Devoxx
Javaslang @ DevoxxJavaslang @ Devoxx
Javaslang @ Devoxx
David Schmitz
 
The java server pages
The java server pagesThe java server pages
The java server pages
Atul Saurabh
 
Learning To Run - XPages for Lotus Notes Client Developers
Learning To Run - XPages for Lotus Notes Client DevelopersLearning To Run - XPages for Lotus Notes Client Developers
Learning To Run - XPages for Lotus Notes Client Developers
Kathy Brown
 
Twitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian NetworkTwitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian Network
Hendy Irawan
 
OpenNTF Webinar 2022-08 - XPages Jakarta EE Support in Practice
OpenNTF Webinar 2022-08 - XPages Jakarta EE Support in PracticeOpenNTF Webinar 2022-08 - XPages Jakarta EE Support in Practice
OpenNTF Webinar 2022-08 - XPages Jakarta EE Support in Practice
Jesse Gallagher
 
Lombok
LombokLombok
Karate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter ThomasKarate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter Thomas
intuit_india
 
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter PilgrimJavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
JavaCro 2014 Scala and Java EE 7 Development Experiences
JavaCro 2014 Scala and Java EE 7 Development ExperiencesJavaCro 2014 Scala and Java EE 7 Development Experiences
JavaCro 2014 Scala and Java EE 7 Development Experiences
Peter Pilgrim
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
ipolevoy
 

Similar to Java SE 8 for Java EE developers (20)

Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidad
 
Fifty New Features of Java EE 7 in Fifty Minutes
Fifty New Features of Java EE 7 in Fifty MinutesFifty New Features of Java EE 7 in Fifty Minutes
Fifty New Features of Java EE 7 in Fifty Minutes
 
Fifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 MinutesFifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 Minutes
 
SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)
SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)
SoTWLG Intro to Code Bootcamps 2016 (Roger Nesbitt)
 
NoSQL Endgame - Java2Days 2020 Virtual
NoSQL Endgame - Java2Days 2020 VirtualNoSQL Endgame - Java2Days 2020 Virtual
NoSQL Endgame - Java2Days 2020 Virtual
 
Sqladria 2009 SRC
Sqladria 2009 SRCSqladria 2009 SRC
Sqladria 2009 SRC
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
 
Tutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component pluginTutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component plugin
 
Javaslang @ Devoxx
Javaslang @ DevoxxJavaslang @ Devoxx
Javaslang @ Devoxx
 
The java server pages
The java server pagesThe java server pages
The java server pages
 
Learning To Run - XPages for Lotus Notes Client Developers
Learning To Run - XPages for Lotus Notes Client DevelopersLearning To Run - XPages for Lotus Notes Client Developers
Learning To Run - XPages for Lotus Notes Client Developers
 
Twitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian NetworkTwitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian Network
 
OpenNTF Webinar 2022-08 - XPages Jakarta EE Support in Practice
OpenNTF Webinar 2022-08 - XPages Jakarta EE Support in PracticeOpenNTF Webinar 2022-08 - XPages Jakarta EE Support in Practice
OpenNTF Webinar 2022-08 - XPages Jakarta EE Support in Practice
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Lombok
LombokLombok
Lombok
 
Karate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter ThomasKarate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter Thomas
 
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter PilgrimJavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
 
JavaCro 2014 Scala and Java EE 7 Development Experiences
JavaCro 2014 Scala and Java EE 7 Development ExperiencesJavaCro 2014 Scala and Java EE 7 Development Experiences
JavaCro 2014 Scala and Java EE 7 Development Experiences
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
 

More from José Paumard

Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19
José Paumard
 
From Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdfFrom Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdf
José Paumard
 
The Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern MatchingThe Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern Matching
José Paumard
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UK
José Paumard
 
Designing functional and fluent API: application to some GoF patterns
Designing functional and fluent API: application to some GoF patternsDesigning functional and fluent API: application to some GoF patterns
Designing functional and fluent API: application to some GoF patterns
José Paumard
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
José Paumard
 
Designing functional and fluent API: example of the Visitor Pattern
Designing functional and fluent API: example of the Visitor PatternDesigning functional and fluent API: example of the Visitor Pattern
Designing functional and fluent API: example of the Visitor Pattern
José Paumard
 
Construire son JDK en 10 étapes
Construire son JDK en 10 étapesConstruire son JDK en 10 étapes
Construire son JDK en 10 étapes
José Paumard
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
José Paumard
 
Asynchronous Systems with Fn Flow
Asynchronous Systems with Fn FlowAsynchronous Systems with Fn Flow
Asynchronous Systems with Fn Flow
José Paumard
 
Java Full Throttle
Java Full ThrottleJava Full Throttle
Java Full Throttle
José Paumard
 
Streams in the wild
Streams in the wildStreams in the wild
Streams in the wild
José Paumard
 
JAX RS and CDI bike the reactive bridge
JAX RS and CDI bike the reactive bridgeJAX RS and CDI bike the reactive bridge
JAX RS and CDI bike the reactive bridge
José Paumard
 
L'API Collector dans tous ses états
L'API Collector dans tous ses étatsL'API Collector dans tous ses états
L'API Collector dans tous ses états
José Paumard
 
Les Streams sont parmi nous
Les Streams sont parmi nousLes Streams sont parmi nous
Les Streams sont parmi nous
José Paumard
 

More from José Paumard (15)

Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19
 
From Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdfFrom Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdf
 
The Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern MatchingThe Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern Matching
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UK
 
Designing functional and fluent API: application to some GoF patterns
Designing functional and fluent API: application to some GoF patternsDesigning functional and fluent API: application to some GoF patterns
Designing functional and fluent API: application to some GoF patterns
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 
Designing functional and fluent API: example of the Visitor Pattern
Designing functional and fluent API: example of the Visitor PatternDesigning functional and fluent API: example of the Visitor Pattern
Designing functional and fluent API: example of the Visitor Pattern
 
Construire son JDK en 10 étapes
Construire son JDK en 10 étapesConstruire son JDK en 10 étapes
Construire son JDK en 10 étapes
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
 
Asynchronous Systems with Fn Flow
Asynchronous Systems with Fn FlowAsynchronous Systems with Fn Flow
Asynchronous Systems with Fn Flow
 
Java Full Throttle
Java Full ThrottleJava Full Throttle
Java Full Throttle
 
Streams in the wild
Streams in the wildStreams in the wild
Streams in the wild
 
JAX RS and CDI bike the reactive bridge
JAX RS and CDI bike the reactive bridgeJAX RS and CDI bike the reactive bridge
JAX RS and CDI bike the reactive bridge
 
L'API Collector dans tous ses états
L'API Collector dans tous ses étatsL'API Collector dans tous ses états
L'API Collector dans tous ses états
 
Les Streams sont parmi nous
Les Streams sont parmi nousLes Streams sont parmi nous
Les Streams sont parmi nous
 

Recently uploaded

Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 

Recently uploaded (20)

Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 

Java SE 8 for Java EE developers

  • 2. @Delabassee @JosePaumard#Devoxx #SE84EE Agenda Java SE 8 has been released ~1.5 year ago Java EE 7 Application Servers - GlassFish, WildFly, Liberty Profile, WebLogic, etc.
  • 3. @Delabassee @JosePaumard#Devoxx #SE84EE Agenda Java SE 8 has been released ~1.5 year ago Java EE 7 Application Servers - GlassFish, WildFly, Liberty Profile, WebLogic, etc. Check some important Java SE 8 new features for Java EE developers... with patterns!
  • 8. The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.
  • 9.
  • 11. Date
  • 12. @Delabassee @JosePaumard#Devoxx #SE84EE New Date & Time API Date & Time API is a new introduction in Java 8 Initiated by Stephen Colebourne, based on Joda Time Complete replacement of Date & Calendar
  • 13. @Delabassee @JosePaumard#Devoxx #SE84EE Date: ZonedTime Useful for localized times Set<String> allZonesIds = ZoneId.getAvailableZoneIds() ; String ukTZ = ZoneId.of("Europe/Paris") ;
  • 14. @Delabassee @JosePaumard#Devoxx #SE84EE Date: ZonedTime Useful for localized times System.out.println( ZonedDateTime.of( 1998, Month.JULY.getValue(), 12, // year / month / day 22, 0, 0, 0, // h / mn / s / nanos ZoneId.of("Europe/Paris")) ); // prints 1998-07-22T22:00-00:01:15[Europe/London]
  • 15. @Delabassee @JosePaumard#Devoxx #SE84EE Date: ZonedTime Useful for localized times System.out.println( ZonedDateTime.of( 1998, Month.JULY.getValue(), 12, // year / month / day 22, 0, 0, 0, // h / mn / s / nanos ZoneId.of("Europe/Paris")) ); ZonedDateTime nextWorldCup = currentWorldCup.plus(Period.ofYear(4));
  • 16. @Delabassee @JosePaumard#Devoxx #SE84EE Date: ZonedTime Useful for localized times System.out.println( ZonedDateTime.of( 1998, Month.JULY.getValue(), 12, // year / month / day 22, 0, 0, 0, // h / mn / s / nanos ZoneId.of("Europe/Paris")) ); ZonedDateTime nextWorldCup = currentWorldCup.plus(Period.ofYear(4)); ZonedDateTime nexWorldCupJapan= nextWorldCup.withZoneSameInstant(ZoneId.of("Asia/Tokyo")) ;
  • 17. @Delabassee @JosePaumard#Devoxx #SE84EE Date: bridges with java.util.Date Conversions between j.u.Date and Date & Time Time time = Time.from(localTime); // API -> legacy LocalTime localTime = time.toLocalTime(); // legacy -> new API Date date = Date.from(localDate); // API -> legacy LocalDate localDate = date.toLocalDate(); // legacy -> new API TimeStamp time = TimeStamp.from(instant); // API -> legacy Instant instant = time.toInstant(); // legacy -> new API Date date = Date.from(instant); // API -> legacy Instant instant = date.toInstant(); // legacy -> new API
  • 18. @Delabassee @JosePaumard#Devoxx #SE84EE Usable in JPA JPA does not support this Date & Time API (yet) But with converters, we can still use it @Entity public abstract class AbstractPersistent { @Convert(converter=DateConverter.class) private Instant instant; }
  • 19. @Delabassee @JosePaumard#Devoxx #SE84EE Usable in JPA The converter is a classical object public class DateConverter implements AttributeConverter<Instant, Date> { public Date convertToDatabaseColumn(Instant instant) { return Date.from(instant); } public Instant convertToEntityAttribute(Date date) { return date.toInstant(); } }
  • 20. @Delabassee @JosePaumard#Devoxx #SE84EE Usable in JPA The converter is a classical object public class DateFormatConverter implements AttributeConverter<ZonedDateTime, String> { public String convertToDatabaseColumn(ZonedDateTime time) { return DateTimeFormatter.ISO_DATE_TIME.format(time); } public ZonedDateTime convertToEntityAttribute(String formated) { return DateTimeFormatter.ISO_DATE_TIME .parse(formated, ZonedDateTime::from); } }
  • 21. @Delabassee @JosePaumard#Devoxx #SE84EE Usable in JPA With JPA converters we can use the types from Date & Time API and map in j.u.l.Date or String
  • 22. @Delabassee @JosePaumard#Devoxx #SE84EE Usable in JSF With a Custom JSF Converter @FacesConverter("instantConverter") public class TimeConverter implements javax.faces.convert.Converter { @Override public Object getAsObject(FacesContext ctx, … , String value) { return Instant.parse(value); } }
  • 23. @Delabassee @JosePaumard#Devoxx #SE84EE Usable in JSF With a Custom JSF Converter... @Override public String getAsString(FacesContext ctx, … , Object value) { DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) .withLocale(Locale.US) .withZone(ZoneId.systemDefault()); return formatter.format((TemporalAccessor) value); } }
  • 24. @Delabassee @JosePaumard#Devoxx #SE84EE Usable in JSF With a Custom JSF Converter<h:form> <h:inputText id = "date” value = "#{order.timestamp}" size = "20" required="true” label = "start" converter = "instantConverter" /> ... @ManagedBean(name="order") @SessionScoped public class myBean implements Serializable{ Instant timestamp; …
  • 26. @Delabassee @JosePaumard#Devoxx #SE84EE Annotations in Java 7 Wrapping annotations An annotation cannot be applied more than once @NamedQueries({ @NamedQuery(name=SELECT_ALL, query="..."), @NamedQuery(name=COUNT_ALL, query="...") }) public class Customer { }
  • 27. @Delabassee @JosePaumard#Devoxx #SE84EE Annotations in Java 8 Java 8 makes it possible! @NamedQuery(name=SELECT_ALL, query="..."), @NamedQuery(name=COUNT_ALL, query="...") public class Customer { }
  • 28. @Delabassee @JosePaumard#Devoxx #SE84EE Bean Validation Suppose we want to validate a parameter public orderdCar order( @CheckCar("VW") Car aCar ) { ... }
  • 29. @Delabassee @JosePaumard#Devoxx #SE84EE Bean Validation Here is the Bean Validation code for @CheckCar @Target({PARAMETER}) @Retention(RUNTIME) @Constraint(validatedBy = CarValidator.class) public @interface CheckCar { Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; String value(); }
  • 30. @Delabassee @JosePaumard#Devoxx #SE84EE Bean Validation And for the validator public class CarValidator implements ConstraintValidator<CheckCar, Car> { private String carBrand; public void initialize(CheckCar constraintAnnotation) { this.carBrand = constraintAnnotation.value(); } public boolean isValid(Car obj, ConstraintValidatorContext ctrCtx) { if (object == null) return true; return (!obj.getBrand().toUpperCase().contains(carBrand)); } }
  • 31. @Delabassee @JosePaumard#Devoxx #SE84EE Bean Validation And the Java 8 trick to make it repeatable @Target({PARAMETER}) @Retention(RUNTIME) @Repeatable(CheckCars.class) @Constraint(validatedBy = CarValidator.class) public @interface CheckCar { Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; String value(); }
  • 32. @Delabassee @JosePaumard#Devoxx #SE84EE Bean Validation And the Java 8 trick to make it repeatable @Target({PARAMETER}) @Retention(RUNTIME) public @interface CheckCars { CheckCar[] value() default{}; }
  • 33. @Delabassee @JosePaumard#Devoxx #SE84EE Bean Validation Suppose we want to validate a parameter public orderdCar order( @CheckCar("VW") @ChechCar("Audi") Car aCar ) { ... }
  • 34. @Delabassee @JosePaumard#Devoxx #SE84EE Type annotations Annotations can be now put on types Example 1: tell that a variable should not be null private @NonNull List<Person> persons = ... ;
  • 35. @Delabassee @JosePaumard#Devoxx #SE84EE Type annotations Annotations can be now put on types Example 1: tell that a variable should not be null Example 2: the content should not be null neither private @NonNull List<Person> persons = ... ; private @NonNull List<@NonNull Person> persons = ... ;
  • 37. @Delabassee @JosePaumard#Devoxx #SE84EE Joining strings New String joiners are coming to the JDK!
  • 38. @Delabassee @JosePaumard#Devoxx #SE84EE Joining strings StringJoiner class And it prints: StringJoiner sj = new StringJoiner(", ") ; sj.add("one").add("two").add("three") ; String s = sj.toString() ; System.out.println(s) ; > one, two, three
  • 39. @Delabassee @JosePaumard#Devoxx #SE84EE Joining strings StringJoiner with prefix / postfix And it prints: StringJoiner sj = new StringJoiner(", ", "{", "}") ; sj.add("one").add("two").add("three") ; String s = sj.toString() ; System.out.println(s) ; > {one, two, three}
  • 40. @Delabassee @JosePaumard#Devoxx #SE84EE Joining strings Also accessible from the String class And it prints: // From the String class, with a vararg String s = String.join(", ", "one", "two", "three"); System.out.println(s); > one, two, three
  • 41. @Delabassee @JosePaumard#Devoxx #SE84EE Joining strings And directly from a List // From a list to a String using the Stream & Collectors API String s = listOfStrings.stream() .collect(Collectors.joining(", ")); System.out.println(s); > one, two, three
  • 42. @Delabassee @JosePaumard#Devoxx #SE84EE Joining strings And directly from a List The result is // From the String class, with a vararg String s = listOfStrings.stream() .collect(Collectors.joining(", ", "{", "}")); System.out.println(s); > {one, two, three}
  • 43. @Delabassee @JosePaumard#Devoxx #SE84EE Support for Base64 decoding After a few years… import java.util.Base64; String txt = "Modern Times!"; String encoded = Base64.getEncoder().encodeToString( txt.getBytes(StandardCharsets.UTF_8)); String decoded = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8);
  • 45. @Delabassee @JosePaumard#Devoxx #SE84EE What is a Stream? A new API A typed interface A new concept
  • 46. @Delabassee @JosePaumard#Devoxx #SE84EE What is a Stream? A new API A typed interface A new concept Let’s see some code!
  • 47. @Delabassee @JosePaumard#Devoxx #SE84EE Readable and efficient patterns Extract histograms from data List<Person> people = Arrays.asList(); Map<City, Double> agesByCity = people.stream() .filter(p -> p.getAge() > 20) .collect( Collectors.groupingBy( Person::getCity, Collectors.averagingDouble(Person::getAge) ) );
  • 48. @Delabassee @JosePaumard#Devoxx #SE84EE Readable and efficient patterns Extract histograms from data List<Person> people = Arrays.asList(); Map<City, Double> agesByCity = people.stream() .filter(p -> p.getAge() > 20) .collect( Collectors.groupingBy( Person::getCity, Collectors.averagingDouble(Person::getAge) ) );
  • 49. @Delabassee @JosePaumard#Devoxx #SE84EE Readable and efficient patterns Extract histograms from data List<Person> people = Arrays.asList(); Map<City, Double> agesByCity = people.stream() .filter(p -> p.getAge() > 20) .collect( Collectors.groupingBy( Person::getCity, Collectors.averagingDouble(Person::getAge) ) );
  • 50. @Delabassee @JosePaumard#Devoxx #SE84EE Readable and efficient patterns Extract histograms from data List<Person> people = Arrays.asList(); Map<City, Double> agesByCity = people.stream() .filter(p -> p.getAge() > 20) .collect( Collectors.groupingBy( Person::getCity, Collectors.averagingDouble(Person::getAge) ) );
  • 51. @Delabassee @JosePaumard#Devoxx #SE84EE Readable and efficient patterns Extract histograms from data List<Person> people = Arrays.asList(); Map<City, Double> agesByCity = people.stream() .filter(p -> p.getAge() > 20) .collect( Collectors.groupingBy( Person::getCity, Collectors.averagingDouble(Person::getAge) ) );
  • 52. @Delabassee @JosePaumard#Devoxx #SE84EE Readable and efficient patterns Extract histograms from data List<Person> people = Arrays.asList(); Map<City, Double> agesByCity = people.stream() .filter(p -> p.getAge() > 20) .collect( Collectors.groupingBy( Person::getCity, Collectors.averagingDouble(Person::getAge) ) );
  • 53. @Delabassee @JosePaumard#Devoxx #SE84EE Building a Stream on a String Building a Stream on the letters of a String: String s = "hello"; IntStream stream = s.chars(); // stream on the letters of s
  • 54. @Delabassee @JosePaumard#Devoxx #SE84EE Building a Stream on a String Building a Stream on the letters of a String: String s = "hello"; IntStream stream = s.chars(); // stream on the letters of s s.chars() // IntStream .mapToObj(letter -> (char)letter) // Stream<Character> .map(Character::toUpperCase) .forEach(System.out::println); // Prints a Character > HELLO
  • 55. @Delabassee @JosePaumard#Devoxx #SE84EE Build a Stream from a text file Find the first error line from a log file // Java 7 : try with resources and use of Paths Path path = Paths.get("d:", "tmp", "debug.log"); try (Stream<String> stream = Files.lines(path)) { stream.filter(line -> line.contains("ERROR")) .findFirst() .ifPresent(System.out::println); } catch (IOException ioe) { // handle the exception }
  • 56. @Delabassee @JosePaumard#Devoxx #SE84EE Build a Stream from a regex Building a Stream from a regexp // book is a looooooooong String Stream<String> words = Pattern .compile(" ") .splitAsStream(book) ;
  • 57. @Delabassee @JosePaumard#Devoxx #SE84EE Build a Stream from a regex Building a Stream from a regexp More efficient than: // book is a looooooooong String Stream<String> words = Pattern .compile(" ") .splitAsStream(book) ; // book is a looooooooong String Stream<String> words = Stream.of(book.split(" "));
  • 58. @Delabassee @JosePaumard#Devoxx #SE84EE Flatmap: Files.lines + regex Splitting a text files into words Stream<String> streamOfLines = Files.lines(path); Function<String, Stream<String>> splitter = line -> Pattern.compile(" ").splitAsStream(line); long numberOfWords = streamOfLines.flatMap(splitter) .map(String::toLowerCase) .distinct() .count();
  • 59. @Delabassee @JosePaumard#Devoxx #SE84EE Why is it important for Java EE? Given this JSON file [ { "name":"Duke", "gender":"m", "phones":[ "home":"650‐123‐4567", "mobile":"650‐111‐2222" ] }, { "name":"Jane", … ] JsonArray contacts = Json.createArrayBuilder() .add(…
  • 60. @Delabassee @JosePaumard#Devoxx #SE84EE Why is it important for Java EE? And some JSON-P magic Map<String, Long> names = contacts.getValuesAs(JsonObject.class).stream() .filter(x -> "f".equals(x.getString("gender"))) .map(x -> (x.getString("name"))) .collect( Collectors.groupingBy( Function.identity(), Collectors.counting() ) );
  • 61. @Delabassee @JosePaumard#Devoxx #SE84EE Why is it important for Java EE? // Today JsonArray names = contacts.getValuesAs(JsonObject.class).stream() .filter(x -> "f".equals(x.getString("gender"))) .map(x -> (x.getString("name"))) .collect( Collector.of( () -> Json.createArrayBuilder(), (builder, value) -> builder.add(value), (builder1, builder2) -> builder1.add(builder2), builder -> builder.build() ) );
  • 62. @Delabassee @JosePaumard#Devoxx #SE84EE Why is it important for Java EE? // Today JsonArray names = contacts.getValuesAs(JsonObject.class).stream() .filter(x -> "f".equals(x.getString("gender"))) .map(x -> (x.getString("name"))) .collect( Collector.of( Json::createArrayBuilder, JsonArrayBuilder::add, JsonArrayBuilder::add, JsonArrayBuilder::build ) );
  • 63. @Delabassee @JosePaumard#Devoxx #SE84EE Why is it important for Java EE? // Today JsonArray names = contacts.getValuesAs(JsonObject.class).stream() .filter(x -> "f".equals(x.getString("gender"))) .map(x -> (x.getString("name"))) .collect( Collectors.collectingAndThen( Collector.of( Json::createArrayBuilder, JsonArrayBuilder::add, JsonArrayBuilder::add ), JsonArrayBuilder::build ) );
  • 64. @Delabassee @JosePaumard#Devoxx #SE84EE Why is it important for Java EE? Collect into JSON Avaiblable through the JsonCollectors factory // Tomorrow, with JSON-P 1.1 JsonArray names = contacts.getValuesAs(JsonObject.class).stream() .filter(x -> "f".equals(x.getString("gender"))) .map(x -> (x.getString("name"))) .collect( JsonCollectors.toJsonArray() );
  • 66. @Delabassee @JosePaumard#Devoxx #SE84EE A warning on parallelism All parallel operations (Streams, ConcurrentHashMap) take place in the common ForkJoinPool The common ForkJoinPool takes all the available cores / CPUs
  • 67. @Delabassee @JosePaumard#Devoxx #SE84EE A warning on parallelism All parallel operations (Streams, ConcurrentHashMap) take place in the common ForkJoinPool The common ForkJoinPool takes all the available cores / CPUs To preserve your Application Server: System.setProperty( "java.util.concurrent.ForkJoinPool.common.parallelism", "1") ;
  • 69. @Delabassee @JosePaumard#Devoxx #SE84EE CompletableFuture New addition to j.u.concurrent Allow to chain asynchronous tasks Use case: test the asynchronous calls in the Servlet API, EJB, JAX-RS, …
  • 70. @Delabassee @JosePaumard#Devoxx #SE84EE Creation of an asynchronous task The Jersey way to create an asynchronous call @Path("/resource") public class AsyncResource { @GET public void asyncGet(@Suspended final AsyncResponse asyncResponse) { new Thread(new Runnable() { public void run() { String result = longOperation(); asyncResponse.resume(result); } }).start(); } }
  • 71. @Delabassee @JosePaumard#Devoxx #SE84EE Creation of an asynchronous task (let us fix this code with Java 8) @Path("/resource") public class AsyncResource { @GET public void asyncGet(@Suspended final AsyncResponse asyncResponse) { executor.submit(() -> { String result = longOperation(); asyncResponse.resume(result); }); } }
  • 72. @Delabassee @JosePaumard#Devoxx #SE84EE How to test it? We want to check if the result object is passed to the resume() method of the asyncResponse It is a very basic test, but tricky to write since we are in an asynchronous world We have mocks for that!
  • 73. @Delabassee @JosePaumard#Devoxx #SE84EE How to test it? We can inject a mock AsyncResponse, even mock the result Then verify the correct interaction: But we need to verify this once the run() method has been called… Mockito.verify(mockAsyncResponse).resume(result);
  • 74. @Delabassee @JosePaumard#Devoxx #SE84EE How to test it? This is where CompletionStage come to the rescue! @Path("/resource") public class AsyncResource { @Inject ExecutorService executor; @GET public void asyncGet(@Suspended final AsyncResponse asyncResponse) { executor.submit(() -> { String result = longOperation(); asyncResponse.resume(result); }); } }
  • 75. @Delabassee @JosePaumard#Devoxx #SE84EE How to test it? @Path("/resource") public class AsyncResource { @Inject ExecutorService executor; @GET public void asyncGet(@Suspended final AsyncResponse asyncResponse) { executeAsync(asyncResponse); } public CompletableFuture<Void> executeAsync(final AsyncResponse asyncResponse) { return CompletableFuture.runAsync(() -> { asyncResponse.resume(longOperation()); }, executor); } }
  • 76. @Delabassee @JosePaumard#Devoxx #SE84EE How to test it? AsyncResource asyncResource = new AsyncResource(); asyncResource.executeAsync(mockAsyncResponse); // returns the CompletableFuture .thenRun(() -> { // then execute this Runnable Mockito.verify(mockAsyncResponse).resume(result); } );
  • 77. @Delabassee @JosePaumard#Devoxx #SE84EE How to test it? Be careful of visibility issues 1) It’s better to run this in the same thread 2) Since the mocks are used and checked in this thread, create them in this thread too
  • 78. @Delabassee @JosePaumard#Devoxx #SE84EE How to test it? So the complete pattern becomes this one 1) First we create our mocks String result = Mockito.mock(String.class); AsyncResponse response = Mockito.mock(AsyncResponse.class); Runnable train = () -> Mockito.doReturn(result).when(response.longOperation()); Runnable verify = () -> Mockito.verify(response).resume(result);
  • 79. @Delabassee @JosePaumard#Devoxx #SE84EE How to test it? So the complete pattern becomes this one 2) Then we create the call & verify Runnable callAndVerify = () -> { asyncResource.executeAsync(response).thenRun(verify); }
  • 80. @Delabassee @JosePaumard#Devoxx #SE84EE How to test it? So the complete pattern becomes this one 3) Then we create the task ExecutorService executor = Executors.newSingleThreadExecutor(); AsynResource asyncResource = new AsyncResource(); asyncResource.setExecutorService(executor); CompletableFuture .runAsync(train, executor) // this trains our mocks .thenRun(callAndVerify); // this verifies our mocks
  • 81. @Delabassee @JosePaumard#Devoxx #SE84EE How to test it? Since a CompletableFuture is also a Future, we can fail with a timeout if the test does not complete fast enough ExecutorService executor = Executors.newSingleThreadExecutor(); AsynResource asyncResource = new AsyncResource(); asyncResource.setExecutorService(executor); CompletableFuture .runAsync(train, executor) // this trains our mocks .thenRun(callAndVerify) // this verifies our mocks .get(10, TimeUnit.SECONDS);
  • 82. @Delabassee @JosePaumard#Devoxx #SE84EE Conclusion Java 8 is not just about lambdas There are also many new and very useful patterns Ready to be used before becoming a lambda ninja! Not covered: - Collection framework - Concurrency, Concurrent hashmap - JavaScript on the JVM with Nashorn - Security