Working with nested Maps in JAVA

In this post I will show you a simple and easy way of working with JAVA Maps, more precisely, how to add an element (a.k.a value) to a multi nested maps:

That’s it. Simple, isn’t it? 😉

Source code: github

Builder Design Pattern

Here is the “usual” implementation of this design pattern.

 

The result is:
builder2

UML
builder2_uml

 

 

Builder Design Pattern (simple way)

This design pattern allows us to create an object with the advantage that the same construction process can create different representations of that object. Here is the simplest implementation of this design pattern.

In a next tutorial we will explain the other way of doing the same thing, with more flexibility but with a more complex implementation.

So, let’s start creating a car!

 

The final result:

builder

Singleton Design Pattern

With his design patttern we allways get the same instance, as you can see next.

  1. The Singleton class:

 

2. The main class:

 

3. The result:

singleton

 

UML
singleton

Reverse String/array recursively

Here is an example how to recursively invert the order of a string or an array in Java.

The output is:

output

Notice that in the string method we have twice the iterations that we have in the array method, because we go through all positions in the string.

If you know other ways of doing it, please feel free to comment it out.

Thanks.

Simple CDI Events Example

In this post I will show you how to produce a CDI event and how to handle it even if it is deployed in another application.

The Event class

A simple JSF Page

This page only shows a simple message from the backing bean (the call to the bean produces the bean’s initialization).

Backing Bean

Here we Inject an event (LoggerEvent) via CDI Inject annotation. Then inside the init method annotated with PostConstruct we fire the event with a new instance of the event. This is the simplest way to fire a CDI event. No matter who are listening to this event will be notified.

A simple Logger Event Handler

This class will listen for events annotated with the keyword @Observes. Because of this, it will execute the method. In this case it will print to the console a log message passed to the constructor of the event instance when it was created: Hello from CDI events as you can see in the next picture.

Result (console result)

cdi events
cdi events

AS you can see, it’s just that simple to create a CDi event and listen to it. This technique uses the Observer design pattern here with the help of @Observes annotation.

Feel free to comment. Download the souce code CDIEvents.

Thanks.