LINQ for Java tool [closed]

LINQ for Java would be lovely, but the problem is the language integration.

Java doesn't have anything as concise as lambda expressions, and they're one of the bedrocks of LINQ. I suppose they could layer the query expression support on top of normal Java without lambda expressions, by making the expansion create anonymous inner classes - but it would be pretty hideous. You'd also need expression trees if you wanted to do anything like LINQ to SQL.

Checked exceptions might get in the way, but we'd have to see. The equivalent of IQueryable would need to have some sort of general checked exception - or possibly it could be generic in both the element type and the exception type...

Anyway, this is all pie-in-the-sky - given the troubles the Java community is having with closures, I think it would be folly to expect anything like LINQ in Java itself earlier than about 2012. Of course, that's not to say it wouldn't be possible in a "Java-like" language. Groovy has certain useful aspects already, for instance.

For the library side, Hibernate already provides a "non-integrated" version of a lot of the features of LINQ to SQL. For LINQ to Objects, you should look at the Google Java Collections API - it's a lot of the same kind of thing (filtering, projecting etc). Without lambdas it's a lot fiddlier to use, of course - but it's still really, really handy. (I use the Google Collections code all the time at work, and I'd hate to go back to the "vanilla" Java collections.)


It's worth noting that Scala 2.8 is going to have LINQ support...


Actually, scala standart collections provide API that works like LINQ-for-Objects in some sense. Here is the example:

List("Paris","Berlin","London","Tokyo")
  .filter(c => c.endsWith("n"))
  .map(c => c.length) 
// result would be length of the words that ends 
// with "n" letter ("Berlin" and "London").

Don't be scared of new-line-dot syntax: you can write code in plain old style:

Array(1,2,3,4,5,6).map(x => x*x)

And there is a number of projects that provide close to LINQ-to-SQL syntax. For example, snippet taken from Squeryll:

import Library._
using(session) { 
  books.insert(new Author(1, "Michel","Folco"))            
  val a = from(authors)(a=> where(a.lastName === "Folco") select(a)) 
}
// but note that there is more code behind this example

For a more general approach to the issue, consider using Querydsl.

It provides a LINQ-style syntax with support for JPA/Hibernate, JDO, SQL and Java Collection backends.

I am the maintainer of Querydsl, so this answer is biased.