Input/Output e Stream in Java
Alex Liu
Software Development Engineer
Trasformazione dei dati con stream
List a Set)ArrayList, LinkedList)HashSet, TreeSet)Keys/Values come Streams) (es. HashMap, TreeMap)Arrays.stream())ArrayList di esempio names usata nel resto del video
names: ["Alice", "Bob", "Charlie", "David"]
Set, Collectors e Streamimport 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();
[Alice, Bob, Charlie, David]// Use `.map()` to convert each element to upper case
Stream<String> upperCaseNameStream = namesStream.map(
name -> name.toUpperCase())
[ALICE, BOB, CHARLIE, DAVID]// use `.collect()` and `Collectors.toSet()` to store the transformed stream data
upperCaseNameStream.collect(Collectors.toSet())
{CHARLIE, ALICE, BOB, DAVID}
Il metodo .reduce()
.reduce() usa due input
0(x, y) -> x + y significa:x è il totale accumulatoy è l’elemento correntey a x finché tutti gli elementi sono processatiArrayList names in uno Stream.Stream<String> stream = names.stream();
.map() per ottenere la lunghezza dei nomi e .reduce() per sommarlestream
.map(name -> name.length())
.reduce(0, (sum, length) -> sum + length);
20Input/Output e Stream in Java