java8-ulissestelemaco
DESCRIPTION
Java 8TRANSCRIPT
JDKAlpha and Beta!
(1995)
JDK 1.0 !(1996)
JDK 1.1 !(1997)
J2SE 1.2!Playground !(1998)
J2SE 1.3!Kestrel !(2000)
J2SE 1.4!Merlin !(2002)
J2SE 5.0 Tiger
(2004)
Java SE 6!Mustang !(2006)
Java SE 7!Dolphin !(2011)
Java SE 8 JSR 337 (2014)
Tks Wikipedia
Spider 8 patas
teia (net)
Generics!Annotations!
Enumerations!varargs!
static imports!new for!
…
project coin
• Function <NEW>!• Stream <NEW>!• Time <NEW>!• Collections!• Concurrency!• IO/NIO!• +…
• Nashorn!• Metaspace!• +…APIs
Linguagem
Infraestrutura
Novidades
Java 8 • Lambdas • Interfaces Funcionais!• Default Method!• Generic Inference (better)!• Type annotation!• +…
(int x, int y) -> {return x + y;};
Lista de parâmetros separadas por vírgula
Bloco da função lambda…
Separador Lambda
1ª INTERFACE FUNCIONAL
public interface MyFuncInterface {!
! public void myMethod();!
}
@FunctionalInterface
2ª INTERFACE FUNCIONAL???
public interface AnotherInterface {!
! public void oneMethod();!
public void anotherMethod();!
}
@FunctionalInterface Erro
new MyFuncInterface() {!
@Override public void myMethod() { System.out.println("XPTO!"); }!
};
() -> { System.out.println("XPTO!”); };
class MyClass {!
public void method( MyFuncInterface mfi ) { ... } !
}
a.method( () -> { System.out.println("XPTO!"); } );
a.method( new MyFuncInterface() {! @Override public void myMethod() { System.out.println("XPTO!");
}
} );
new SomeInterface() {! @Override! public someType someMethod(args) {! body! }!}
(args) -> {body} Resumo: forma de
instanciar uma
classe anônima!!!
INFERÊNCIA DE TIPOS
(x) -> x*10; public int method(int x);
(x) -> x.length(); public int method(String x);
(x,y) -> x.add(y);void method(List<String> x,!
String y);
int
String
java.util.List<String>
String
List<String> anyStringList = new ArrayList<>();!
// ...!
anyStringList.sort( !
(a,b) -> Integer.compare(a.length(), b.length())!
);
+ 1EXEMPLO…
LAMBDA & METHOD REFERENCE
p -> p.getName(); Person::getName;
x -> String.valueOf(x); String::valueOf;
() -> new ArrayList(); ArrayList::new;
+METHOD REFERENCE
(Person p) -> { return p.getName();};
anyMethod ( p -> p.getName() );
anyMethod ( Person::getName );
STATIC METHODpublic interface MyInterface {!
! public static void someMethod() {!
//do something...!
! }!
}
DEFAULT METHODpublic interface AnotherInterface {!
! public default int anotherMethod() {!
return 100;!
! }!
public int toDefineMethod();!
}
JAVA.UTIL.FUNCTIONS
NEW!!!
"Functional interfaces provide target types for lambda expressions and method references.”
Javadoc
INTERFACES FUNCIONAIS…
1. Function<T, R> !
2. Predicate<T> !
3. Consumer<T> !
4. Supplier<T>!
5. BinaryOperator<T>
INTERFACES FUNCIONAIS…
1. Function<T, R> !
2. Predicate<T> !
3. Consumer<T> !
4. Supplier<T>!
5. BinaryOperator<T>
Representa uma “função” que recebe como
parâmetro um objeto do tipo T e retorna um
objeto do tipo R.
/**! * Represents a function that accepts! * one argument and produces a result.! * …! * @since 1.8! */!@FunctionalInterface!public interface Function<T, R> {!! /**! * Applies this function to the! * given argument.! *! * @param t the function argument! * @return the function result! */! R apply(T t);!…!}
<R> Stream<R> map(Function<? super T,? extends R> mapper)Returns a stream consisting of the results of applying the given function to the elements of this stream.
<R> Stream<R> flapMap(Function<? super T,? extends Stream> mapper) Returns a stream consisting of the results of applying the given function to the elements of this stream.
java.util.stream Interface Stream<T> (parte 1)
EXEMPLO FUNCTION
Function<Person, String> f1 = p -> p.getName();
Function<Person, String> f2 = Person::getName;
myStream.map( p -> p.getName() );
myStream.map( Person::getName );
INTERFACES FUNCIONAIS…
1. Function<T, R> !
2. Predicate<T> !
3. Consumer<T> !
4. Supplier<T>!
5. BinaryOperator<T>
Representa uma “predicado” que recebe como parâmetro um objeto do tipo T e retorna
um objeto booleano.
INTERFACES FUNCIONAIS…
1. Function<T, R> !
2. Predicate<T> !
3. Consumer<T> !
4. Supplier<T>!
5. BinaryOperator<T>
Representa uma “consumidor” que recebe como parâmetro
um objeto do tipo T e não tem valor de retorno.
INTERFACES FUNCIONAIS…
1. Function<T, R> !
2. Predicate<T> !
3. Consumer<T> !
4. Supplier<T>!
5. BinaryOperator<T>
Representa uma “produtor” que não tem parâmetro. e
retorna um objeto do tipo T.
INTERFACES FUNCIONAIS…
1. Function<T, R> !
2. Predicate<T> !
3. Consumer<T> !
4. Supplier<T>!
5. BinaryOperator<T>
Representa uma “operador binário” que recebe dois parâmetros do tipo T e retorna um objeto também do tipo
T.
Stream<T> filter(Predicate<? super T> predicate)Returns a stream consisting of the elements of this stream that match the given predicate.
void forEach(Consumer<? super T> action)Performs an action for each element of this stream.
Optional<T> reduce(BinaryOperator<? super T> accumulator)Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.
static <T> Stream<T>
generate(Supplier<? super T> s)Returns an infinite sequential unordered stream where each element is generated by the provided Supplier.
java.util.stream Interface Stream<T> (parte 2)
+ DERIVADOS…• BiFunction<T,U,R> !
• BiPredicate<T,U> !
• BIConsumer<T,U> !
• -!
• -
• IntFunction<R> !
• IntPredicate !
• IntConsumer !
• IntSupplier!
• IntBinaryOperator
• LongFunction<R> !
• LongPredicate !
• LongConsumer !
• LongSupplier!
• LongBinaryOperator
+ Double, InToLong,…
+ JAVA.UTIL.FUNCTIONS• 43 Interfaces funcionais…
• functional method
• largamente usada nas novas APIs (Stream, NIO, Collection, etc)
STREAM
• Fornece uma API "fluente" (fluent-api) para operação sobre um conjunto sequencial (stream) de valores…
STREAM• Fornece uma API "fluente" (fluent-api) para
operação sobre um conjunto sequencial (stream) de valores…
List<String> names = ..;!
Stream<String> stream = names.stream();
int sumChars = names.stream()!
.filter( n -> n.startsWith(“A") )!
.mapToInt( n -> n.length() )!
.sum();
STREAM• Fornece uma API "fluente" (fluent-api) para
operação sobre um conjunto sequencial (stream) de valores…
List<String> names = ..;!
Stream<String> stream = names.stream();!
int sumChars = names.stream()!
.filter( n -> n.startsWith(“A") )!
.mapToInt( n -> n.length() )!
.sum();
STREAM• Fornece uma API "fluente" (fluent-api) para
operação sobre um conjunto sequencial (stream) de valores…
int sumChars = names.stream()!
.filter( n -> n.startsWith(“A") )!
.mapToInt( n -> n.length() )!
.sum();
STREAM• Fornece uma API "fluente" (fluent-api) para
operação sobre um conjunto sequencial (stream) de valores…
int sumChars = names.stream()!
.filter( n -> n.startsWith(“A") )!
.mapToInt( n -> n.length() )!
.sum();
Filtra os nomes que começam com a letra “A”, transforma a lista de String numa lista de inteiros que representa
a quantidade de caracteres para cada
nome filtrado, soma o resultado e retorna.
STREAM• Fornece uma API "fluente" (fluent-api) para
operação sobre um conjunto sequencial (stream) de valores…
int sumChars = names.stream()!
.filter( n -> n.startsWith(“A") )!
.mapToInt( n -> n.length() )!
.sum();
Filtra os nomes que começam com a letra “A”, transforma a lista de String numa lista de inteiros que representa
a quantidade de caracteres para cada
nome filtrado, soma o resultado e retorna.
names.stream()!
.distinct()!
.forEach(System.out::println);
STREAM• Fornece uma API "fluente" (fluent-api) para
operação sobre um conjunto sequencial (stream) de valores…
int sumChars = names.stream()!
.filter( n -> n.startsWith(“A") )!
.mapToInt( n -> n.length() )!
.sum();
Filtra os nomes que começam com a letra “A”, transforma a lista de String numa lista de inteiros que representa
a quantidade de caracteres para cada
nome filtrado, soma o resultado e retorna.
names.stream()!
.distinct()!
.forEach(System.out::println);
Remove os nomes duplicados da lista e
imprime o resultado.
STREAM… PRINCIPAIS FEATURES…
map Executa uma transformação 1-para-1 a partir da Function informada
filter Exclui os objetos que não atendem à Predicate
forEach Executa uma ação Consumer em cada objeto do Stream
collect“Coleta" os elementos do Stream em
outra estrutura (Collection, Map, String, etc)
i
i
t
t
LAMBDA STREAM FUNCTIONcollection.stream()!
.filter( n -> n.startsWith(“A") )!
.map( functionLambda )!
.peek( consumerLambda )!
.filter( predicateLambda )!
.flapMap( functionLambda )!
.sorted( comparatorLambda )!
.forEach( consumerLambda );
INTERMEDIATE X TERMINAL• Fluent-api… permite
sequenciamento de operações… retorna stream….
• Mantém o stream “aberto”,
• Lazy
• filter, map, flatMap, peek, distinct, sorted, limit, skip…
•• Operação final
• Dispara a execução de todas as operações intermediárias (lazy)…
• Após ser invocado o stream é fechado…
• forEach, toArray, reduce, collect, min, max, sum, count, anyMatch, allMatch, noneMatch, findFirts, findAny…
names.stream()
.map( … )
.peek( … );
.flapMap( … )
.sorted( … );
.forEach( … );
Intermediate
Terminal
RECEITA STREAM
Ingredientes:
• 1 fonte de dados (normalmente uma collection)
Modo de Preparo:
1. Obtenha o objeto stream a
partir da fonte de dados
!
2. Aplique uma ou mais
operações intermediárias
!
3. Aplique uma operação
terminal.
SEQUENTIAL & PARALLEL
• Sequential (default) x Parallel
• ForkJoinPool.commonPool()
• Stateless J x Stateful L
... = names.stream();!
... = names.parallelStream();
LocalTime Hora, minuto e segundo 10:15:30
LocalDate Ano, mês e dia 2007-12-13
LocalDateTime Ano, mês, dia, hora, minuto e segundo
2007-12-03T10:15:30
YearMonth Ano e mês 2007-12
MonthDay Mês e dia 12-03
InstantRepresenta um instante
no tempo!(similar ao java.utilDate)
2014-09-14T22:26:22.819Z
Duration Quantidade de tempo em horas 34.5 seconds
Period Quantidade de tempo em dias
2 years, 3 months and 4 days
+ CONCEITOSZonedDateTime, OffsetDateTime, OffsetTime, ZoneOffset
FACTORY METHOD!
... = LocalTime.now();
... = LocalTime.of(8,10);!
... = LocalDate.now();
... = LocalDate.of(2014,9,25);!
... = LocalDateTime.now();
... = LocalDateTime.of(2014,9,25,8,8);
LocalTime time = now.plusHours(4) .plusMinutes(30) .plus(1, ChronoUnit.MINUTES) .minusSeconds(100);!
!
ajuste = TemporalAdjusters.next(DayOfWeek.WEDNESDAY); LocalDate nextWed = today.with(ajuste) .withHour(3);
+ FLUENT, +CLEAN, +SIMPLE
IMMUTABLE!!!
LocalTime time = now.plusHours(4) .plusMinutes(30) .plus(1, ChronoUnit.MINUTES) .minusSeconds(100);!
!
ajuste = TemporalAdjusters.next(DayOfWeek.WEDNESDAY); LocalDate nextWed = today.with(ajuste) .withHour(3);
+ FLUENT, +CLEAN, +SIMPLE
IMMUTABLE!!!
now não sofre alteração.
today não sofre alteração.
nextWed = LocalDate.now().with( TemporalAdjusters.next(DayOfWeek.WEDNESDAY) );
VEJA TAMBÉM…• Period & Duration!
• DateTimeFormatter!
• TemporalAdjuster
COLLECTIONS API
• stream() e parallelStream()
• vários métodos utilitários…
• finalmente sort()!!!
• lambda & functions
Mudanças
na API
• Iterable.forEach(Consumer)
• Collection.removeIf(Predicate)
• Collection.spliterator()
• Collection.stream()
• Collection.parallelStream()
• List.sort(Comparator)
• List.replaceAll(UnaryOper)
!
• Map.putIfAbsent(K, V)
• Map.remove(Object, Object)
• Map.replace(K, V, V)
• Map.computeIfAbsent(K, Func)
• Map.computeIfPresent(K, BiFunc)
• Map.compute(K, BiFunction)
• Map.merge(K, V, BiFunction)
• Map.getOrDefault(Object, V)
CONCURRENCY API (1)1.ForkJoinPool.commonPool()
2.StampedLock - ReentrantReadWriteLock
3.+ java.util.concurrent.atomic.LongAdder+ java.util.concurrent.atomic.LongAccumulator + java.util.concurrent.atomic.DoubleAdder + java.util.concurrent.atomic.DoubleAccumulator
CONCURRENCY API (2)CompletableFuture
• Future que pode ser “completado" .!
• Fluent-API
• Lambda!!!CompletableFuture<String> future;!
future = CompletableFuture.supplyAsync( lambdaSupplier ) .thenRun( lambdaConsumer ) .thenApply( lambdaFunction ) .thenApply(…) … .whenComplete( lambdaBiConsumer );!
…
CONCURRENCY API (2)CompletableFuture
• Future que pode ser “completado" .!
• Fluent-API
• Lambda!!!
CompletableFuture<String> future;!
future = CompletableFuture.supplyAsync( lambdaSupplier ) .thenRun( lambdaConsumer ) .thenApply( lambdaFunction ) .thenApply(…) … .whenComplete( lambdaBiConsumer );!
… future.complete(“Default Value”); //COMPLETED!!! …!
while(!future.isDone()) { //... }!
String result = future.get();!!
CONCURRENCY API (2)CompletableFuture
• Future que pode ser “completado" .!
• Fluent-API
• Lambda!!!
CompletableFuture<String> future;!
future = CompletableFuture.supplyAsync( lambdaSupplier ) .thenRun( lambdaConsumer ) .thenApply( lambdaFunction ) .thenApply(…) … .whenComplete( lambdaBiConsumer );!
… future.complete(“Default Value”); //COMPLETED!!! …!
while(!future.isDone()) { //... }!
String result = future.get();!!
IO/NIO API• basicamente métodos que tratam a
fonte de dados como Stream<?>…
• BufferedReader.lines()
• Files.find(Path, BiPredicate,…)
!
• Files.walk(Path, ...)
• Files.list(Path)
• Files.lines(Path,…)
Mudanças
na API
TYPE ANNOTATION
• Checker Frameworkhttp://types.cs.washington.edu/checker-framework/ !
• Annotation em qualquer declaração de tipo !
• ElementType.TYPE_PARAMETER, ElementType.TYPE_USE
NEW!!! JSR-308
@NotNull String str1 = …!
@Email String str2 = …!
@NotNull @NotBlank String str3 = …!
!
class Folder<F extends @Existing File> { ... }!
List<@Immutable ? extends Comparable<T>> unchangeable = …!
!
new @NonEmpty @Readonly List<String>(myNonEmptyList)!
!
void method() throws @Critical AnyException { ... }
@NotNull String str1 = …!
@Email String str2 = …!
@NotNull @NotBlank String str3 = …!
!
class Folder<F extends @Existing File> { ... }!
List<@Immutable ? extends Comparable<T>> unchangeable = …!
!
new @NonEmpty @Readonly List<String>(myNonEmptyList)!
!
void method() throws @Critical AnyException { ... }
Java 8 somente provê
o mecanismo de anotar
qualquer declaração de
tipo.