1 of 24

PROGRAMAÇÃO FUNCIONAL NO JAVA 17 Reaprendendo a programar com Lambdas e Streams

Prof Manoel Campos, Instituto Federal de Educação do Tocantins�

https://git.io/Je3Uo

https://bio.link/manoelcampos

2 of 24

COMO PROCESSAMOS DADOS EM UMA LISTA EM JAVA? ⚙️

2

3 of 24

UTILIZAMOS UM LAÇO DE REPETIÇÃO, CERTO? 🔁

for(int i = 0; i < listaEstudantes.size(); i++){

System.out.println(listaEstudantes.get(i));

}

3

4 of 24

QUAIS OS PROBLEMAS DESTE LOOP? 🤔

for(int i = 0; i < listaEstudantes.size(); i++){

System.out.println(listaEstudantes.get(i));

}

4

5 of 24

ESTE CÓDIGO É SIMPLES? 🤨

for(int i = 0; i < listaEstudantes.size(); i++){

System.out.println(listaEstudantes.get(i));

}

5

6 of 24

NÃO, NÃO É! 😝

6

7 of 24

Isto é simples 🙌🏼

  • x = x + 1

7

8 of 24

  • Aquele loop é apenas familiar 🤔

A Arte da Simplicidade https://youtu.be/6nghH0D9_Fg(legendado)

8

9 of 24

COMO PODEMOS SIMPLIFICAR AQUELE LOOP? �🔁

9

10 of 24

for each, claro! 🙄

for(Estudante estudante: listaEstudantes){

System.out.println(estudante);

}

10

11 of 24

O LOOP AQUI NÃO É O QUE DESEJAMOS FAZER DE FATO

11

12 of 24

É apenas um meio para um fim: processar a lista de alunos�

12

13 of 24

PROCESSANDO UMA LISTA

Como obter estatísticas de alunos em uma lista?

  • maior nota
  • menor nota
  • total por sexo
  • etc

13

14 of 24

PROCESSANDO UMA LISTA

int maiorNota;

for(Estudante estudante: listaEstudantes){

if(estudante.getNota() > maiorNota)

maiorNota = estudante.getNota();

}

System.out.println("Maior nota é " + maiorNota)

14

15 of 24

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

16 of 24

Problemas desse código 🧐

  • Suscetível a bugs
  • Mutabilidade

16

17 of 24

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

18 of 24

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+).

19 of 24

COMO FAZER MELHOR? 🤔

19

20 of 24

ACERTOU QUEM DISSE “PROGRAMAÇÃO FUNCIONAL” 😎👏🙌

20

21 of 24

MÃOS À OBRA

  1. imprimeMaiorNota: Stream, map (mapToInt, mapToDouble...) com lambda
  2. imprimeMaiorNotaHomens:
    1. filter e lambda, orElseThrow e NoSuchElementException
    2. criar método isMale e usar method reference (no getScore tbm)
  3. imprimeTotalHomens
  4. imprimeMediaNotas: média das notas de alunos
  5. imprimeTotalEstudantesMatriculados (filter): obter o curso do aluno e contar quantos estão matriculados em um curso
  6. imprimeTotalCampiComAlunos (maps sucessivos): pegar curso, depois campus e contar o total de campi em que há alunos (de forma distinta)
  7. imprimeEstudantesAprovadosTSI (map e toList): criar Student::hasCourse, obter lista de alunos de um curso com um determinado código
  8. imprimeEstudantesAgrupandoPorCurso (agrupando alunos por curso): Collectors.groupingBy unário
  9. imprimeTotalEstudantesPorCurso (agrupando e contando): Collectors.groupingBy counting
  10. imprimeMediaNotasAgrupandoPorSexo: groupingBy averaging
  11. imprimeEstudantesAprovadosPalmas (concatenando alunos): map e Collectors.joining()
  12. Mostrar relação das entradas e saídas do map no depurador do IntelliJ
  13. Ordenação padrão: fazendo Course implementar Comparable.
  14. Ordenação com Stream.sort
  15. Invertendo ordenação com Comparator.reserve
  16. Combinando Comparators.

21

22 of 24

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

23 of 24

PARA SABER MAIS 🤓

Código Fonte, Slides e material complementar no GitHub

https://git.io/Je3Uo

23

24 of 24

24