-
-
Save JoseRFJuniorLLMs/283b107d54cfa1740777c8973bc6d214 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