Created
September 23, 2019 17:39
-
-
Save cleuton/3572ac7502357dd7f71bc7418d05974d to your computer and use it in GitHub Desktop.
Java Stream API demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.obomprogramador.stream; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.function.Supplier; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
public class StreamDemo { | |
public static void main(String[] args) { | |
List<Double> valores = new ArrayList<Double>(Arrays.asList(1.45,2.10,2.10,3.67)); | |
Stream<Double> stNumeros = valores.stream(); | |
// Imprimindo: O Stream é de uso único | |
System.out.println(stNumeros); // Não funciona | |
stNumeros.forEach(s -> System.out.println(s)); | |
//stNumeros.forEach(System.out::println); // Erro: stream has already been closed | |
// Usando Supplier: Podemos usar a sintaxe "double colon" para invocar métodos em Lambda | |
Supplier<Stream<Double>> stSup = () -> Stream.of(valores.toArray(Double[]::new)); | |
stSup.get().forEach(s -> System.out.println(s)); | |
stSup.get().forEach(System.out::println); | |
// Filter: | |
stSup.get().filter(v -> v < 3).forEach(System.out::println); | |
// Map: | |
List<Float> flist = stSup.get().map(v -> v.floatValue()).collect(Collectors.toList()); | |
System.out.println(flist.get(1).getClass().getName()); | |
// Distinct: | |
stSup.get().distinct().forEach(System.out::println); | |
// Reduce: | |
System.out.println(stSup.get().reduce((x,y) -> x*y)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment