Trasformazione dei dati con Stream

Input/Output e Stream in Java

Alex Liu

Software Development Engineer

Trasformazione dei dati con stream

  • Trasformazione dei dati con stream

    • Converti formati, aggrega e filtra
    • Salva i risultati in un altro tipo di collection (es. da List a Set)
    • Collection supportate:
      • Liste (es. ArrayList, LinkedList)
      • Set (es. HashSet, TreeSet)
      • Map (Keys/Values come Streams) (es. HashMap, TreeMap)
      • Array (con Arrays.stream())
  • ArrayList di esempio names usata nel resto del video

    names: ["Alice", "Bob", "Charlie", "David"]
    
Input/Output e Stream in Java

Usare Stream per trasformare gli elementi

  • Preparazione: importa le classi necessarie Set, Collectors e Stream
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

// Convert the `ArrayList` we created earlier `names` to a `Stream` Stream<String> namesStream = names.stream();
  • Dati attuali: [Alice, Bob, Charlie, David]
Input/Output e Stream in Java

Usare Stream per trasformare gli elementi (continua)

// Use `.map()` to convert each element to upper case
Stream<String> upperCaseNameStream = namesStream.map(
        name -> name.toUpperCase())
  • Dati attuali: [ALICE, BOB, CHARLIE, DAVID]
// use `.collect()` and `Collectors.toSet()` to store the transformed stream data
upperCaseNameStream.collect(Collectors.toSet())
  • Dati finali:
    {CHARLIE, ALICE, BOB, DAVID}
    
Input/Output e Stream in Java

Usare Stream per l'aggregazione

  • Il metodo .reduce()

    • Aggrega gli elementi in un unico risultato
    • Utile per somma, concatenazione o min/max
  • .reduce() usa due input

    • Valore iniziale: punto di partenza, es. 0
    • Operatore binario: funzione con due argomenti
      • (x, y) -> x + y significa:
        • x è il totale accumulato
        • y è l’elemento corrente
        • Aggiungi y a x finché tutti gli elementi sono processati
Input/Output e Stream in Java

Usare Stream per l'aggregazione: esempio

  • Converti l'ArrayList names in uno Stream.
    Stream<String> stream = names.stream();
    
  • Usa .map() per ottenere la lunghezza dei nomi e .reduce() per sommarle
    stream
      .map(name -> name.length())
      .reduce(0, (sum, length) -> sum + length);
    
  • Risultato: 20
Input/Output e Stream in Java

Passiamo alla pratica !

Input/Output e Stream in Java

Preparing Video For Download...