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:

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());


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:


[1] JavaTM Tutorials - Lambda Expressions
[2] JavaDoc - Interface Predicate<T>
[3] JavaTM Tutorials - The Collection Interface
[4] Processing Data with Java SE 8 Streams, Part 1

Thursday, 4 February 2016

Validation of Beans

Just a small utility function that prints out readable messages on what is wrong with a certain bean (like for example a JPA Entity).

Got a little miffed with the fact that my javax.validation.ConstraintViolationException that is thrown, never shows the exact problem. I always have to drill down into the Exception to find the message in order to fix the problem.

I hope it helps someone.

See for more information about bean validation JSR 303.


The Java EE 6 Tutorial - Using Bean Validation
The Java EE 6 Tutorial - Validating Persistent Fields and Properties