Lambda Expression in JAVA 8

Do you remember Anonymous Class, easy game isn’t it ? but is it enough clear and easy to read? I don’t think so.
Anonymous class are in general used to pass a functionality as an argument to an other method (likes Event, Listener) by implementing often only one method that makes code more verbose and unclear.
But Java 8 introduces a new gate to functional programming (FP) by introducing Lambda Expression which makes clean and readable code easy to maintain and more coherent.

So What is Lambda?

In the Java Specification (Click here), Lambda is defined as a block of parameters and code  that can be used to pass function as a parameter.

To illustrate this let implement Runnable using the old and new fashion of Java coding .
In Java 7 and previous, the only way to do it is by doing this:

Runnable runnableOldFachion = new Runnable() {
			
			@Override
			public void run() {
				/* your code here*/
			}
		};

With java 8 we can  do it also  this way

Runnable runnableNewFachion = ()-> {/*your code here*/};

WaW so clean. imagine so the combination of the two programming approach, functional (FP) and object oriented (OOP). imagine the strength while doing reactive programming, map reducing, data aggregation, data filtering and  searching or even  high multi threading concurrent programming.
I advice you to look inside this and start any new project using java 8. this will help you to understand this concept.
Note: People who  never develop in Schem or Lisp, will encounter some trouble to understand the FP concepts, but don’t stop keep learning and exercising, then everything will be easy and clear.

Here it is an simple use case  of FP in java 8

/**
 * 
 */
package java_8__spec_test;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import java_8__spec_test.Vehicle.VehicleType;

/**
 * FP Example inside JAVA 8
 * 
 * @author Younss Azzayani
 *
 */
class Vehicle {
	/**
	 * Vehicle Type.
	 * */
	enum VehicleType {
		BICYCLE(0), MOTORCYCLE(1), CAR(2), TRUCK(3), OTHER(4);
		int type;

		VehicleType(int type) {
			this.type = type;
		}

	}

	/**
	 * Vehicle Reference
	 */
	String referenceCode;
	/**
	 * Vehicle Type
	 */
	VehicleType type;

	/**
	 * Constructor
	 * 
	 * @param referenceCode
	 * @param type
	 */
	public Vehicle(String referenceCode, VehicleType type) {
		if (referenceCode == null || type == null) {
			throw new RuntimeException("reference and type must not be null ");

		}
		this.referenceCode = referenceCode;
		this.type = type;
	}

	@Override
	public String toString() {
		return type + " [" + referenceCode + "]";
	}

	/**
	 * Compare current object with given object as param.
	 * 
	 * @param b
	 * @return
	 */
	public int compareByType(Vehicle b) {
		return this.type.type >= b.type.type ? 1 : -1;
	}
}

/**
 * Lambda Sample
 * 
 * @author Younss AZZAYANI
 *
 */
public class LambdaSample {

	/**
	 * 
	 * @param args
	 */
	public static void main(String... args) {
		/* Lets have a Collection of Vehicle */
		List<Vehicle> vehicles = Arrays.asList(new Vehicle("c0",
				VehicleType.CAR), new Vehicle("c2", VehicleType.CAR),
				new Vehicle("b0", VehicleType.BICYCLE), new Vehicle("t0",
						VehicleType.TRUCK), new Vehicle("m0",
						VehicleType.MOTORCYCLE));

		System.out.println("*** 1- Show Vehicles first aproch");
		vehicles.forEach((p) -> {
			System.out.println(p.toString());
		});
		/* Sort Example 1st approch */
		Collections.sort(vehicles, Vehicle::compareByType);
		/* Sort Example 2d approch */
		Collections.sort(vehicles, (v1, v2) -> v1.type.type >= v2.type.type ? 1
				: -1);

		System.out.println("*** 2- Show Vehicles second aproch");
		vehicles.forEach(System.out::println);
		/* filter all cars from original vehicle collection */
		List<Vehicle> cars = vehicles.stream()
				.filter((v) -> v.type.equals(VehicleType.CAR))
				.collect(Collectors.toList());

		System.out.println("*** 3- Show Cars:");
		cars.forEach(System.out::println);

	}

}

Advertisements
About

A java Developer interested in Big Data,NoSQL, Functionnal and Dynamic programming

Posted in Java_corner

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: