Skip to content

Instantly share code, notes, and snippets.

@JoseRFJuniorLLMs
Forked from cleuton/StreamDemo.java
Created November 7, 2019 11:25
Show Gist options
  • Save JoseRFJuniorLLMs/283b107d54cfa1740777c8973bc6d214 to your computer and use it in GitHub Desktop.
Save JoseRFJuniorLLMs/283b107d54cfa1740777c8973bc6d214 to your computer and use it in GitHub Desktop.
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