PROGRAMAÇÃO FUNCIONAL NO JAVA 17 Reaprendendo a programar com Lambdas e Streams
Prof Manoel Campos, Instituto Federal de Educação do Tocantins�
COMO PROCESSAMOS DADOS EM UMA LISTA EM JAVA? ⚙️
2
UTILIZAMOS UM LAÇO DE REPETIÇÃO, CERTO? 🔁
for(int i = 0; i < listaEstudantes.size(); i++){
System.out.println(listaEstudantes.get(i));
}
3
QUAIS OS PROBLEMAS DESTE LOOP? 🤔
for(int i = 0; i < listaEstudantes.size(); i++){
System.out.println(listaEstudantes.get(i));
}
4
ESTE CÓDIGO É SIMPLES? 🤨
for(int i = 0; i < listaEstudantes.size(); i++){
System.out.println(listaEstudantes.get(i));
}
5
NÃO, NÃO É! 😝
6
Isto é simples 🙌🏼
7
8
COMO PODEMOS SIMPLIFICAR AQUELE LOOP? ��🔁
9
for each, claro! 🙄
for(Estudante estudante: listaEstudantes){
System.out.println(estudante);
}
10
O LOOP AQUI NÃO É O QUE DESEJAMOS FAZER DE FATO
11
É apenas um meio para um fim: processar a lista de alunos�
12
PROCESSANDO UMA LISTA
Como obter estatísticas de alunos em uma lista?
13
PROCESSANDO UMA LISTA
int maiorNota;
for(Estudante estudante: listaEstudantes){
if(estudante.getNota() > maiorNota)
maiorNota = estudante.getNota();
}
System.out.println("Maior nota é " + maiorNota)
14
O que há de errado?
int maiorNota;
for(Estudante estudante: listaEstudantes){
if(estudante.getNota() > maiorNota)
maiorNota = estudante.getNota();
}
System.out.println("Maior nota é " + maiorNota)
15
Problemas desse código 🧐
16
MUTABILIDADE
The root of all evil�(mas não leve ao pé da letra)
�https://medium.com/google-developer-experts/learning-to-use-and-abuse-mutability-b4c71576299
17
Img: wondriumdaily.com
JDK 16 até introduziu records (immutable data classes)
record Country(String name, String continent) {
}
var country = new Country("Portugal", "Europe");
// country.name = "Brazil"; // 🧨 name é privado
// country.setName("Brazil"); // 🧨 não existe setter
System.out.println(country);�System.out.printf("%s: %s", country.name(), country.continent());
18
Teste o código no jshell, sem precisar criar uma classe com um método main pra isso (JDK 16+).
COMO FAZER MELHOR? 🤔
19
ACERTOU QUEM DISSE “PROGRAMAÇÃO FUNCIONAL” 😎👏🙌
20
MÃOS À OBRA
21
PRINCIPAIS INTERFACES FUNCIONAIS
Consumer �(egoísta: recebe algo e não dá nada em troca)
BiConsumer �(egoísta: recebe em dobro e não dá nada em troca)
Supplier �(altruísta: dá algo sem pedir nada em troca)
22
Predicate
Function
BiFunction
Imagens: pixabay.com | maxpixel.net | en.wikipedia.org/wiki/Function_(mathematics) | clipart-library.com
PARA SABER MAIS 🤓
Código Fonte, Slides e material complementar no GitHub
23