8/06/2013

lambdaj - Express Business Rules in Psuedo English Syntax

I came across this framework  called  'lambdaj' when I was looking for ways to manipulate a collection without writing loops.

lambdaj is a library that makes easier to address this issue by allowing to manipulate collections in a pseudo-functional and statically typed way. With lot of few sugar methods lambdaj gives the ability to express the business rules of your application in pseudo-english syntax. I remember reading somewhere these are part of Java 8 bundle already!!!!

This is a proven, simple and eaze to use library. If there are similar frameworks, let me know.

Sample Code:
TestLambdaj.java

package com.scjp;

import static ch.lambdaj.Lambda.forEach;
import static ch.lambdaj.Lambda.joinFrom;
import static ch.lambdaj.Lambda.maxFrom;
import static ch.lambdaj.Lambda.min;
import static ch.lambdaj.Lambda.on;
import static ch.lambdaj.Lambda.sort;
import java.util.Arrays;
import java.util.List;

public class TestLambdaj {

    public static void main(String[] args) {
        Person p1 = new Person("Harry", 50);
        Person p2 = new Person("Dave", 70);
        Person p3 = new Person("Wilson", 30);
        Person p4 = new Person("Mark", 20);

        List persons = Arrays.asList(p1, p2, p3, p4);
        // Sort the collection by Age
        List sortedAge = sort(persons, on(Person.class).getAge());
        System.out.println(sortedAge);   //Output: [Mark - 20, Wilson - 30, Harry - 50, Dave - 70]


        // Sort the collection by Name
        List sortedName = sort(persons, on(Person.class).getName());
        System.out.println(sortedName); //Output:[Dave - 70, Harry - 50, Mark - 20, Wilson - 30]

        // Find the max Age in the collection
        float maxAge = maxFrom(persons).getAge();
        System.out.println(maxAge);//Output:70.0

        // Find the min Age in the collection
        float minAge = min(persons, on(Person.class).getAge());
        System.out.println(minAge); //Output:20.0

        // Print all the names of the person
        String names = joinFrom(persons).getName();
        System.out.println(names); //Output:Harry, Dave, Wilson, Mark

        // Set the age of all elements inside the collection to 20
        forEach(persons).setAge(20);
        System.out.println(p1.getAge()); //Output:20
    }

}



Person.java
package com.scjp;

public class Person {

    private String name;
    private int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return this.name + " - " + this.age;
    }

}

No comments:

dzone.com