English 中文(简体)
Is there something like LINQ for Java? [closed]
原标题:

Started to learn LINQ with C#.
Especially LINQ to Objects and LINQ to XML.
I really enjoy the power of LINQ.

I learned that there is something called JLINQ a JavaScript implementation.
Also (as Catbert posted) Scala will have LINQ

Do you know if LINQ or something similar will be a part of Java 7?

Update: Interesting post from 2008 - LINQ for Java tool

最佳回答

Look at Scala, which is powerful functional programming language, but is similar to Java and runs on Java platform.

In Scala it is possible to use essentially the same code constructs as in LINQ, albeit without special query comprehensions syntax present in C# or VB.

EDIT :

Here s an example of Scala s querying capabilities :

// Get all StackOverflow users with more than 20,000 reputation points.
val topUsers = for{
    u <- users
    if u.reputation > 20000
} yield u;

println ("Users with more than 20,000 reputation:")
for (u <- topUsers) {
    println u.name
}
问题回答

It s important to note that LINQ are four things:

  • Monadic comprehension
  • Database integration
  • SQL-like syntax
  • AST manipulation

People who just have heard of it may think of it simply as database integration. People who have worked a little with it probably think of SQL-like syntax. Those who really dug in will be aware of the monadic comprehension aspect of it, even if they don t know it for what it is.

If one takes Scala, for example, it has monadic comprehension without the other three. There is a library called ScalaQuery which provides database integration through the monadic comprehension (the intrinsic ability to do so being the main reason monads are cool). Another project, called ScalaQL, I think, intends to provide pretty much the same thing, but using a compiler plugin to enhance it. I wasn t aware of Miguel Garcia s work you mentioned, but, having seen other stuff he has accomplished, I m thrilled by it.

One doesn t need special syntax to do monadic comprehension, however. It just makes it uncluttered by boilerplate. So that aspect of it is instantly available to languages with the right level of generics support.

Two things Scala doesn t do. The first is SQL-like syntax. That much can t be helped: SQL syntax looks out of place in Scala. I think it s safe to say most Scala programmers would prefer to stay with what is familiar to them -- the so-called for comprehensions.

The other thing is the one I haven t discussed yet, AST manipulation. That is the ability to manipulate code that has been parsed by the compiler, but not yet transformed in byte code, granting the ability to alter it before the generation is completed.

I think such a thing would be a boon to Scala -- heck, to any language. But, then again, I have a background as a Forth programmer, where the ability to alter code as it was being compiled was a God-given right. .Net can do it through LINQ, and so can some other languages, such as Ruby.

LINQ would be hard in Java due to the current lack of closures. Assuming Java 7 really does get reasonably compact closure support and extension methods, LINQ in terms of "dot notation" should be feasible even if it doesn t get the equivalent of query expressions.

The Google Collections Library (now at 1.0 - but to be replaced by Guava when that is ready) contain many of the required methods - and I wouldn t be surprised to see 101 LINQ-like APIs spring up as soon as the closure support looks reasonably final.

I can t see (at the moment) Java getting anything like expression trees, however - so I suspect you ll be limited to LINQ to Objects unless you have custom compilation.

Check out Quaere. It s a LINQ-like DSL for Java that you can include as a library. Example:

// Get all StackOverflow users with more than 20,000 reputation points.
Iterable<User> topUsers = from("u").in(entityManager.entity(User.class)).
    where(gt("u.getReputation()", 20000)).
    select("u");

System.out.println("Users with more than 20,000 reputation:");
for (User u : topUsers) {
    System.out.println(u.getName());
}

However, note that Java doesn t have a concept analogous to extension methods. Whatever s in Quaere is pretty much what you re stuck with; if you need to make your own special utilities, they ll probably have to be in separate utility classes (ick).

Additionally, because Java < 7 has no native closures, you re stuck with strings to reference things, and your IDE can t introspect those to show you problems if you mistype something. (A smarter IDE might be able to handle this shortcoming, however, if somebody were to write introspection plugins for Quaere.)

By using the lambdaj library you can find the top reputation users as it follows:

List<User> topUsers = 
    select(users, having(on(User.class).getReputation(), greaterThan(20000)));

It has some advantages respect the Quaere library because it doesn t use any magic string, it is completely type safe and in my opinion it offers a more readable DSL.

You could try diting which implements chainable query methods on a collection.

   Integer[] values = new Integer[] {0,1,2,3,4,5,6,7,8,9,10};

   Enumerable<Integer> query = new Enumerable<Integer>(values).where(new Predicate<Integer>(){

    @Override
    public boolean evaluate(Integer value) throws Exception {
        return value % 2 == 0;
    }});

   for(Integer i : query)
   {
       System.out.write(i);
       System.out.write( 
 );
   }

CQEngine or Collection Query Engine http://code.google.com/p/cqengine/ seems extremely promising. Haven t tried it though. It allows you to build indices over collections and query them. Supposed to be very quick.

Is there something as simple to use as LINQ-2-SQL on the JVM? I want to generate entities (classes) from the DB scheme using some tool and use those to interact directly with the DB. Is there an XML-free solution? I don t want to have to annotate the classes. In .NET, the tool is called sqlmetal. It s sort of a pre-processor that generates all the DB classes, so to speak.

Once this is done, I think it ll be fairly easy to use Scala s built in language constructs.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签