Thursday 11 February 2016

My First Lambda

I just implemented my first lambda1. My java code is now officially only Java 8 and up compliant.

My pom was changed as follows:
<project.source.version>1.8</project.source.version>
<project.target.version>1.8</project.target.version>

Original code

The original code looked like this:
Pretty straight forward stuff.

Adding a Lambda

Then we received two change requests, that could be resolved by re-using the method above.

But this time, not everyone was required to see the message. In other words, the list of active players needed to be filtered.

Enter the Predicate2.

Let us say the filtering needs to be done, by those who wish to be kept in the loop regarding roleplaying events. These users contain an Ooc (Out-of-Character) flag.

Calling this can be done using a Lambda, like so:
sendWall("[OOC: " + aUser.getName() + "] " + message + "\r\n", p -> p.getOoc());

Streams

To make things a little more complicated, you can make use of the new Streams3 4 provided in Java 8.

In the example below, I take a stream from the List collection provided by getActivePlayers, filter it by the predicate, and run the writeMessage on each found user. That last one is called a "terminator" as it terminates the stream, i.e. it "does something".

A lot less code than the previous for loop. It seems more complicated, but I guess it just requires me to get used to it.

It also causes me to create another Lambda, as the terminator.

The Old Way

In the old way, calling this method sendWall was done using an inner class, and it looked as follows:

References

[1] JavaTM Tutorials - Lambda Expressions
https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
[2] JavaDoc - Interface Predicate<T>
https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html
[3] JavaTM Tutorials - The Collection Interface
https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
[4] Processing Data with Java SE 8 Streams, Part 1
http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html


No comments:

Post a Comment