开发者

Linq like for Java [duplicate]

This question already has answers here: 开发者_开发技巧 What is the Java equivalent for LINQ? [closed] (34 answers) Is there something like LINQ for Java? [closed] (8 answers) Closed 9 years ago.

I have experience in C# programming, but I need to change something in Java project, so my question is IS THERE IN JAVA ANYTHING SIMILAR LINQ IN C# ? I need to query lists in Java.


It depends on what you want to do, exactly. C#'s notion of lambda notation can be mimicked much more verbosely using anonymous classes. So you could create a Where method that takes a Function<T, bool>, where Function<T1, TReturn> is a class that has a single method (e.g. Execute). I understand Guava has something like this.

The idea would be to then say something like this:

Iterable<Ball> redBalls = Enumerable.Where(balls, 
    new Function<Ball, bool>() {
        public bool Execute(Ball b) { return b.getColor() == Color.Red; }
    });

But for all this work, you might as well have done it sans Linq:

List<Ball> redBalls = new ArrayList<Ball>();
for(Ball ball in balls) {
    if(ball.getColor() == Color.Red) {redBalls.add(ball);}
}

Unfortunately, it's a far cry from what you can do when you combine lambda expressions, inferred types, properties, and extension methods, the way C# does.

var redBalls = balls.Where(b => b.Color == Color.Red);

Code like this will only be possible when Java implements lambda expressions, which was scheduled for version 7, but got pushed back to the "next version". And things like LINQ to SQL or LINQ to Entities will only be possible if they get Expression trees, which I don't think is even in the roadmap.

Edit

Some people have come up with complex libraries to simulate this behavior, though. Many use "magic strings" to perform the portions of the queries that they can't provide compiler-checked values. LambdaJ uses proxy objects to make the compiler think that you're working with one of your objects, which allows you to call getter and setter methods with compile checks, looking something like this:

List<Person> redBalls = filter(having(
    on(Ball.class).getColor(), equalTo(Color.RED)), 
    balls);

These are very clever, but none can really match the simplicity of LINQ at this point in time.


There's nothing that resembles LINQ for Java. Sorry. By googling I found this project but of course you cannot expect the same integration into the language or a syntactic sugar you might get in C#.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜