Linq like DSL in java in few lines of code

13Apr09

This is what happens when you are reading a great functional programming book , looking at imperative code makes you cry . Here is what I did to console myself out of my grief today ( whatever makes you happy right ? )

The code below wraps google collections , in a thin java DSL like wrapper

 public class IterableQuery {

   public static  Where from(Iterable originalCollection) {
      return  new Where( Iterables.transform(originalCollection, IterableQuery.SAME()));
   }

   private static  Function SAME() {
      return new Function(){
         public T apply(T arg0) {
            return arg0;
         }
      };
   }

   public static class SelectOrderBy{

      private final Iterable iterable;

      public SelectOrderBy(Iterable iteable) {
         this.iterable = iteable;
      }

      public  SelectOrderBy orderyBy( Comparator sort ){
          Ordering.forComparator(sort).sort((List) iterable);
          return new SelectOrderBy( iterable);
      }

      public   Iterable select(  Function function){
         return Iterables.transform(iterable, function);
      }
      public  Iterable selectEveryThing( ){
         return iterable;
      }
   }

   public static class Where{

      private final Iterable iterable;

      public Where(Iterable iterable) {
         this.iterable = iterable;
      }

      public    SelectOrderBy where(Predicate predicate) {
         return  new SelectOrderBy( Iterables.filter(iterable, predicate));
      }
   }

}

Now collections could be queried like

 Iterable currentlyAssigned =
             IterableQuery.
              from(orders).
              where(placedInLast10Days).
              orderBy(lastName).
              select(orderToNewOrder);
Advertisements


No Responses Yet to “Linq like DSL in java in few lines of code”

  1. Leave a Comment

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: