Skip to content

Instantly share code, notes, and snippets.

@parambirs
Created August 29, 2019 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parambirs/740f6d000098fac638a883be30997c85 to your computer and use it in GitHub Desktop.
Save parambirs/740f6d000098fac638a883be30997c85 to your computer and use it in GitHub Desktop.
Creating different kinds of Stream sources in Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Sources {
public static void main(String[] args) throws IOException {
// Collections
Stream<String> typesOfFruits = List.of(
"apple", "banana", "clementine", "dragonfruit"
).stream();
// I/O
Stream<String> lines = Files.lines(Path.of("my-fruit-list.txt"));
// Generators
Random random = new Random();
Stream<Integer> randomNumbers = Stream.generate(random::nextInt);
// -----------------------
// Intermediate operations
// -----------------------
// Same length: returns a Stream of "APPLE", "BANANA", "CLEMENTINE", "DRAGONFRUIT"
typesOfFruits.map(String::toUpperCase);
// Shorter: this returns a Stream of "clementine", "dragonfruit"
typesOfFruits.filter(fruit -> fruit.length() > 7);
// Longer: returns a Stream of "a", "p", "p", "l", "e", "b", "a" ...
typesOfFruits.flatMap(fruit -> Stream.of(fruit.split("")));
// These operations return a Stream of all the letters in the fruit names which
// are after "G" in the alphabet, uppercased: "P", "P", "L", "N"...
typesOfFruits
.map(String::toUpperCase)
.flatMap(fruit -> Stream.of(fruit.split("")))
.filter(s -> s.compareTo("G") > 0);
// -------------------
// Terminal operations
// -------------------
// Collecting the Stream elements into a List
List<String> fruitList = typesOfFruits.collect(Collectors.toList());
// Doing something with each element of the Stream
typesOfFruits.forEach(System.out::println);
// How many elements are in the Stream?
long fruitCount = typesOfFruits.count();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment