Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java Stream API demo
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
You can’t perform that action at this time.