[devcamp] usando programação funcional agora!
TRANSCRIPT
Usando programação funcional agora!
Rodrigo [email protected]
Quem sou eu?
● Trabalho com desenvolvimento há 10 anos
● Trabalho com Java há 8 anos
● Arquiteto de Software na CI&T
● Nerd
[email protected] twitter :(
Programação Funcional 101
Java 8
Pensa em uma lista
List<String> herois = Arrays.asList("Batman", "Super Man", "Iron Man", "Hulk", "Flash", "Spider Man");
@Test
public void lambda() {
for(String heroi: herois){
System.out.println(heroi);
}
}
@Test
public void lambda() {
herois.forEach(new Consumer<String>() {
public void accept(String heroi) {
System.out.println(heroi);
}
});
}
@Test
public void lambda() {
herois.forEach(
(String heroi) -> {
System.out.println(heroi);
}
);
}
@Test
public void lambda() {
herois.forEach(heroi->System.out.println(heroi));
}
@Test
public void lambda() {
herois.forEach(System.out::println);
}
Adicionando magia negra!
● Uma sequência de "trens" que suporta operações agregadas de forma sequencial ou paralela
O que é stream
Stream<String> heroisStream = herois.stream();
//Um Stream pode ser dividido em 3 partes
// 1 - Estrutura inicial (resposável por criar o Stream)
herois.stream()
// 2 - Estrutura intermediária, que é resposável por
// executar as funcões que você deseja
.filter(s -> s.startsWith("S"))
// 3 - Estrutura terminal, que é resposável por realizar
// a finalização do fluxo, é decidir qual vai ser o resultado
.collect(Collectors.toList());
● Collection.steam()● Arrays.stream(Object[])● Stream.of(Object[])● IntStream.range(int, int)● IntStream.rangeClosed(int, int)● BufferedReader.lines()● Files.list(path)●
Estrutura inicial
● filter● map● sorted● flatMap● flatMapDouble● limit● skip● etc
Estrutura intermediária
● collect● max● mim● sum● count● toArray● allMatch● anyMatch● etc
Estrutura final
● sorted● unsorted● distinct● parallel● sequential
Estruturas auxiliares
Considerando as funções...
E o paralelismo que comentei?!
Face the brutal facts!
Saia daqui hoje, e use na segunda!
● Comparator <-> <java>● Function <-> Transform● Predicate <-> Predicate*● Consumer <-> Closure● Collector <-> (CollectionUtils.select...)● Criar Nova <-> -
Java8 vs Commons Collection
akie
ras@
cian
dt.c
om
CollectionUtils
Traz "métodos" comuns em linguagens funcionais:
● Collection collect(Collection c, Transformer t)● boolean exists(Collection c, Predicate p)● void filter(Collection c, Predicate p)● Object find(Collection c, Predicate p)● void forAllDo(Collection c, Closure cl)● Collection select(Collection c, Predicate p)● Collection selectRejected(Collection c, Predicate p)● void transform(Collection c, Transformer t)
akie
ras@
cian
dt.c
om
akie
ras@
cian
dt.c
om
akie
ras@
cian
dt.c
om
akie
ras@
cian
dt.c
om
akie
ras@
cian
dt.c
om
akie
ras@
cian
dt.c
om
Nem tudo são flores
Mudança de paradigma é árduo
Em alguns casos precisamos de estado
Por que me apaixonei?!
Código mais expressivo.
Legibilidade.
Testes, teste, teste.
Resumindo
THANKS FOR
BEINGHERE!