menu sluiten
Contact

Antwerpen
Veldkant 33B, 2550 Kontich
België +32 (0)3 444 11 08

Breda
Rithmeesterpark 50-A1, 4838GZ Breda
Nederland +32 (0)3 444 11 08

info@jstack.eu

19 March 2016

Lambda functions: streams

In a previous post, we saw how functional interfaces work, now let’s use them in the Stream API. This API was added in Java 8 release. A Stream, in it simplest form, is just a sequence of elements coming from a source and used to perform some action upon it. In this chapter, I’d like to demonstrate the use of Lambda in the Stream API.

About streams

If you’re already familiar with Streams, you can skip to the next chapter, if not, here’s a small introduction. In Java, a List is used to efficiently manage and access a bunch of items. It’s a datastore. A Stream on the other hand, is used for the consumption of items, coming from a datastore. Check out the following code:

1
2
3
4
5
6
List listStr = Arrays.asList("one","two","three","four");
Stream streamStr = listStr.stream().sorted();
List listStrSorted = streamStr.collect(Collectors.toList());
for (String str : listStrSorted) {
System.out.println(str);
}

First we make a list of Strings, and then we create a stream from it in order to sort them. From the result, we can make a new list, containing the sorted items. So it’s : List -> Stream -> do some stuff -> List again.
Here we sort the items, but we could also change, add, remove items, or execute aggregated functions upon them. The possibilities of Streams are endless, as you will see in the next chapters.

Consumer in the stream API

Now we have seen how to create a Stream, let’s demonstrate how we can use the Consumer interface as a Lambda expression in that Stream API. Remember that the Consumer interface has 1 abstract method : void accept(T t)
The following method will perform, or better ‘consume’ an action, for each element of the stream.
void forEach(Consumer action)
Let’s do the same thing as the example above, but now using a Lambda.

1
2
List listStr = Arrays.asList("one","two","three","four");
listStr.stream().sorted().foreach(str -> System.out.println(str));

The method forEach has 1 parameter that is a Consumer interface.
So here, in the forEach method parameter, an implementation of a Consumer is created, passing the code (the system.out.println) as an implementation of the accept method of the Consumer. It will sort the items and print them in sorted order.

Function in the stream API

Using Lambda , we can also provide an implementation for the Function interface. We’ll use the following method:
Stream map(Function mapper)
This method is used to map each element in a stream to another element, and return a stream of the new elements. We define the actual mapping in a Lambda function, mapping each string to its Integer counterpart.

1
2
3
4
5
6
Stream strm = Stream.of("one","two","three","four");
strm.map(e -> { if (e.equals("one")) return new Integer(1);
else if (e.equals("two")) return new Integer(2);
else if (e.equals("three")) return new Integer(3);
else if (e.equals("four")) return new Integer(4);
else return null; }).forEach(e -> System.out.println(e));

The abstract method in Function is R apply(T t). So it takes an argument and returns an object.
In our example, the if statement is the implementation of our Function. It takes a String, maps it to an Integer, and returns that Integer.
As an extra,instead of putting the elements in a new Stream , we immediately print the elements of the stream by chaining the forEach method. As done in the previous chapter.

Supplier in the stream API

To demonstrate the supplier, let’s take following method:
static Stream generate(Supplier s)
This method generates an infinitive no. of elements.

1
Stream.generate(() -> new Random().nextInt()).limit(10).forEach(e -> System.out.println(e));

The abstract method of Supplier is
T get()
In this example, the implementation of this method is new Random().nextInt().
Then we chain the result to limit(10) which gives us only 10 integers, and then we chain the foreach method, in order to print the 10 random integers.

When you are starting with Java 8, be sure to check the Stream API. It has loads of methods and features to make your life easy, and the maintainer of your code happy.

Meer weten?

Neem contact op met Jasper. Hij denkt graag met u mee in een persoonlijk gesprek.

info@jstack.eu +31 (0)85-888 33 31

Interessant? Deel dit artikel met een vriend(in) of collega!

Vragen over dit onderwerp?

Onze experts denken graag met u mee


    Gerelateerde berichten