Print elements in a stream

System.out.println is often used by developers for debugging purposes to examine elements or objects values present. Java 8 introduced streams so let's find out how to print out elements in a stream using a lambda or method reference.

Detailed Video Notes

While better choice of capturing output of your program would be to choose a logging library such as commons logging, log4j you might be running a local java example where you want a light weight solution. Many developers turn to writing output to the console using System.out.print. With the introduction of streams in java 8, lets find out how we print the contents of a stream to the console.

Getting started

[0:20]

There are two concepts to understand before we dive into the code is method reference and lambdas.

Method references

Method references is a shorthand way to call a method directly which allows you to reuse existing method definitions. It is often a cleaner approach to refer to the existing method by name vs creating a lambda expression. The oracle java tutorials explain the kinds of method references. In our snippet we will reference the static method println so we will call ContainingClass::staticMethodName

KindExample
Reference to a static methodContainingClass::staticMethodName
Reference to an instance method of a particular objectcontainingObject::instanceMethodName
Reference to an instance method of an arbitrary object of a particular typeContainingType::methodName
Reference to a constructorClassName::new

Lambda

Lambda, introduced in java 8, provides a clean and concise way to call method while eliminating anonymous inner functions. In the wild they can typically be written like (int x, int y) -> x + y.

Project set up

[1:2]

Generating a java project from a maven archetype we will update the project to use java 8 and add the dependencies of junit.

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>

Printing stream with method reference

[1:9]

First we need to create a Stream by using stream utility Stream.of which will create a sequential ordered stream of strings. Next calling the foreach, a terminal stream operation, we will pass in System.out::println which will loop over the elements and print the value. You can consider this a short hand way for looping over elements in an ArrayList.

Let's run our test to see the result.

@Test
public void print_elements_stream_method_reference() {

    Stream.of("One", "Two", "Three", "Four").forEach(System.out::println);
}

Printing with lambda

[1:31]

Using another type of stream, IntStream we will use the same technique we just showed you of creating a stream. Instead of using a method reference we will use a lambda expression which reads, pass each element of the stream to the System.out.println.

Let's run our test to see the result.

@Test
public void print_elements_stream_lambda() {

    IntStream.of(1, 2, 3, 4).forEach(
            element -> System.out.println(element));
}

Little fun

[1:46]

You can see using the lambda expression gives you more flexibility especially if you want to append or change the element you are outputting. For instance, lets say before we loop over the elements we want to add 1 to each of the numbers. We can do this by using the lambda, calling the System.out and adding 1.

Let's run our test to see the result.

@Test
public void print_elements_stream_fun() {

    IntStream.of(1, 2, 3, 4).forEach(
            element -> System.out.println(element + 1));
}

We hope that this tutorial showed you a few different ways to use foreach to loop over and print out the elements in a stream.

Thanks for joining in today's level up, have a great day!