Tuesday, 11 September 2012

LinQ in java

In c# there is feature called LinQ, Using LinQ we can execute a query to the Object.
Suppose we have a animal object which contains name of the different animals and respective id.Now I have to find the all the animal whose name contains alphabet 'o'. In C# it is too easy through LinQ, but if you are a java programmer it is little bit difficult and time consuming, we have to write 10-15 line of the code for this functionality.
So make it easy in java i created a jar which having the classes,these class will take care of the code, we just have to write a query that all we have to do. If we use this jar file we same LinQ similar kind of functionality in java. Now i going to show you one example, How we can use the jar file.

I have a class with the name of Animal, containing name of the animal and id.
see the below snap-shot of the class

As the snap shot we have two attribute as name and id. we have a parametrized constructor having two argument name and id.
Now time to copy the jar file into the class path.
Create one more class with any name , i created LinqJava.java
In this class we have import static function of the CollectionFilter class which is part of the jar.

Create the animal Objects.

Animal is the object on which we have to execute the query. our aim was to get the animal name which contains alphabet 'o'.

Write below query

Above query will return list of animal object whose name contains alphabet 'o'.
form , where and contains are static method of CollectionFilter class.getName is the method of the Animal class which returns name.
If we write query based on the id then we have to pass getId method name.

We can perform other operations like Equals ,Not,Greater than, Less than and Is Null operations. we also can user Or and ANd operaor in the Query.

Equals Operation -> List a = from(animal).where("getName", eq("cat")).all();

Not Operation ->List a =from(animal).where("getName", not(eq("cat"))).all();

Less Than -> Only work with number.

Greater Than -> Only work with number.

OR Operator -> from(animal).where("getNme", eq("cat")).or("getId", eq("7")).all();

AND Operator->from(animal).where("getName",contains("o")).and("getId",eq("7")).all();

You Can download the jar Click Here