Java 8 - Streams in action

We will start with What Java 8 streams are and then pipeline aka aggregate operations, how to create streams with examples.

Previous posts

1. What are Streams?

Java 8 introduced new package java.util.stream which contains classes to perform SQL-like operations on elements. Stream is a sequence of elements on which you can perform aggregate operations (reduction, filtering, mapping, average, min, max etc.). It is not a data structure that stores elements like collection but carries values often lazily computed from source through pipeline.

2. What is a pipeline?

A pipeline is sequence of aggregate (reduction and terminal) operations on the source. It has following components.

Points to remember about Streams

3. How to create Streams?

  1. In Collection, you can create streams by calling stream(), parallelStream().
Collection<Person> persons = StreamSamples.getPersons();
persons.stream().forEach(System.out::println);

// parallel stream
persons.parallelStream().forEach(System.out::println);
  1. From Stream interface, calling static factory method of() which takes varargs of T type.
Stream.of("This", "is", "how", "you", "create", "stream", "from", "static", "factory",
"method").map(s -> s.concat(" ")).forEach(System.out::print);
  1. From Arrays class, by calling stream() static method.
Arrays.stream(new String[] { "This", "is", "how", "you", "create", "stream", ".",
"Above", "function", "use", "this" }).map(s -> s.concat(" "))
.forEach(System.out::print);
  1. From Stream by calling iterate(). It is infinite stream function.
// iterate return infinite stream... beware of infinite streams
Stream.iterate(1, i -> i++).limit(10).forEach(System.out::print);
  1. From IntStream class by calling range method.
int sumOfFirst10PositiveNumbers = IntStream.range(1, 10).reduce(0, Integer::sum);
System.out.println(sumOfFirst10PositiveNumbers);
  1. From Random class by calling ints(). It is infinite stream function.
// random.ints for random number
new Random().ints().limit(20).forEach(System.out::println);
  1. From BufferedReader by calling lines(). Streams of file paths can be obtained by calling createDirectoryStream of Files class and some other classes like JarFile.stream(), BitSet.stream() etc.
try (BufferedReader br = new BufferedReader(new StringReader(myValue))) {
br.lines().forEach(System.out::print);
System.out.println();
}
catch (IOException io) {
System.err.println("Got this:>>>> " + io);
}

I hope the post is informative and helpful in understanding Streams. You can find the full example code on Github.



Tags: java.util.stream package, Aggregate operations, Java 8 streams, Java 8 parallel reductions, Java, Java 8

← Back home