[java] What is the Java equivalent for LINQ?

What is Java equivalent for LINQ?

This question is related to java linq

The answer is


There's a very good library that you can use for this.

Located here: https://github.com/nicholas22/jpropel-light

Lambdas won't be available until Java 8 though, so using it is a bit different and doesn't feel as natural.


Scala.Now i star read it , and found it like linq but more simple and more unreadable. but scala can run at linux,yes? csharp need mono.


Java LINQ to SQL implementation. Provides full language integration and larger feature set compared to .NET LINQ.


Lambdas are now available within Java 8 in the form of JSR-335 - Lambda Expressions for the JavaTM Programming Language

UPDATE: JDK8 has now been released which contains project lambda. It's worth grabbing a copy of Java 8 in Action currently still MEAP.

Have a read of Brian Goetz articles relating to lambdas for a decent understanding of how lambdas are implemented within JDK8 while also gaining an understanding of streams, internal iteration, short-circuiting and constructor references.. Also check out the JSR's above to get further examples.

I've written a blog on some of the advantages of using lambdas in JDK8 called The Power of the Arrow, also NetBeans 8 has great support for converting constructs to JDK8 which I've also blogged about Migrating to JDK 8 with NetBeans.


There is an alternate solution, Coollection.

Coolection has not pretend to be the new lambda, however we're surrounded by old legacy Java projects where this lib will help. It's really simple to use and extend, covering only the most used actions of iteration over collections, like that:

from(people).where("name", eq("Arthur")).first();
from(people).where("age", lessThan(20)).all();
from(people).where("name", not(contains("Francine"))).all();

There is a project called quaere.

It's a Java framework which adds the ability to query collections.

Note: According to the author, the project is not maintained anymore.


LINQ to Objects - JAVA 8 has added the Stream API which adds support for functional-style operations on streams of values:

Package java.util.stream

Java 8 Explained: Applying Lambdas to Java Collections

LINQ to SQL/NHibernate/etc. (database querying) - One option would be to use JINQ which also uses the new JAVA 8 features and was released on Feb 26, 2014 on Github: https://github.com/my2iu/Jinq

Jinq provides developers an easy and natural way to write database queries in Java. You can treat database data like normal Java objects stored in collections. You can iterate over them and filter them using normal Java commands, and all your code will be automatically translated into optimized database queries. Finally, LINQ-style queries are available for Java!

JINQ project site: http://www.jinq.org/


I tried guava-libraries from google. It has a FluentIterable which I think is close to LINQ. Also see FunctionalExplained.

List<String> parts = new ArrayList<String>();  // add parts to the collection.    
FluentIterable<Integer> partsStartingA = 
    FluentIterable.from(parts).filter(new Predicate<String>() {
        @Override
        public boolean apply(final String input) {
            return input.startsWith("a");
        }
    }).transform(new Function<String, Integer>() {
        @Override
        public Integer apply(final String input) {
            return input.length();
        }
    });

Seems to be an extensive library for Java. Certainly not as succinct as LINQ but looks interesting.


https://code.google.com/p/joquery/

Supports different possibilities,

Given collection,

Collection<Dto> testList = new ArrayList<>();

of type,

class Dto
{
    private int id;
    private String text;

    public int getId()
    {
        return id;
    }

    public int getText()
    {
        return text;
    }
}

Filter

Java 7

Filter<Dto> query = CQ.<Dto>filter(testList)
    .where()
    .property("id").eq().value(1);
Collection<Dto> filtered = query.list();

Java 8

Filter<Dto> query = CQ.<Dto>filter(testList)
    .where()
    .property(Dto::getId)
    .eq().value(1);
Collection<Dto> filtered = query.list();

Also,

Filter<Dto> query = CQ.<Dto>filter()
        .from(testList)
        .where()
        .property(Dto::getId).between().value(1).value(2)
        .and()
        .property(Dto::grtText).in().value(new string[]{"a","b"});

Sorting (also available for the Java 7)

Filter<Dto> query = CQ.<Dto>filter(testList)
        .orderBy()
        .property(Dto::getId)
        .property(Dto::getName)
    Collection<Dto> sorted = query.list();

Grouping (also available for the Java 7)

GroupQuery<Integer,Dto> query = CQ.<Dto,Dto>query(testList)
        .group()
        .groupBy(Dto::getId)
    Collection<Grouping<Integer,Dto>> grouped = query.list();

Joins (also available for the Java 7)

Given,

class LeftDto
{
    private int id;
    private String text;

    public int getId()
    {
        return id;
    }

    public int getText()
    {
        return text;
    }
}

class RightDto
{
    private int id;
    private int leftId;
    private String text;

    public int getId()
    {
        return id;
    }

    public int getLeftId()
        {
            return leftId;
        }

    public int getText()
    {
        return text;
    }
}

class JoinedDto
{
    private int leftId;
    private int rightId;
    private String text;

    public JoinedDto(int leftId,int rightId,String text)
    {
        this.leftId = leftId;
        this.rightId = rightId;
        this.text = text;
    }

    public int getLeftId()
    {
        return leftId;
    }

    public int getRightId()
        {
            return rightId;
        }

    public int getText()
    {
        return text;
    }
}

Collection<LeftDto> leftList = new ArrayList<>();

Collection<RightDto> rightList = new ArrayList<>();

Can be Joined like,

Collection<JoinedDto> results = CQ.<LeftDto, LeftDto>query().from(leftList)
                .<RightDto, JoinedDto>innerJoin(CQ.<RightDto, RightDto>query().from(rightList))
                .on(LeftFyo::getId, RightDto::getLeftId)
                .transformDirect(selection ->  new JoinedDto(selection.getLeft().getText()
                                                     , selection.getLeft().getId()
                                                     , selection.getRight().getId())
                                 )
                .list();

Expressions

Filter<Dto> query = CQ.<Dto>filter()
    .from(testList)
    .where()
    .exec(s -> s.getId() + 1).eq().value(2);

There are many LINQ equivalents for Java, see here for a comparison.

For a typesafe Quaere/LINQ style framework, consider using Querydsl. Querydsl supports JPA/Hibernate, JDO, SQL and Java Collections.

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


you can try this library: https://code.google.com/p/qood/

Here are some reasons to use it:

  1. lightweight: only 9 public interface/class to learn.
  2. query like SQL: support group-by, order-by, left join, formula,...etc.
  3. for big data: use File(QFS) instead of Heap Memory.
  4. try to solve Object-relational impedance mismatch.

There is no equivalent to LINQ for Java. But there is some of the external API which is looks like LINQ such as https://github.com/nicholas22/jpropel-light, https://code.google.com/p/jaque/


You won't find an equivalent of LINQ unless you use the javacc to create your own equivalent.

Until that day when someone finds a viable way to do so, there are some good alternatives, such as


You can select the items in a collection (and much more) in a more readable way by using the lambdaj library

https://code.google.com/archive/p/lambdaj/

It has some advantages over 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.


JaQu is the LINQ equivalent for Java. Although it was developed for the H2 database, it should work for any database since it uses JDBC.


It sounds like the Linq that everyone is talking about here is just LinqToObjects. Which I believe only offers functionality that can already be accomplished today in Java, but with really ugly syntax.

What I see as the real power of Linq in .Net is that lambda expressions can be used in a context requiring either a Delegate or an Expression and will then be compiled into the appropriate form. This is what allows things like LinqToSql (or anything other than LinqToObjects) to work, and allows them to have a syntax identical to LinqToObjects.

It looks like all of the projects referred to above are only offering the capabilities of LinqToObjects. Which makes me thing that LinqToSql-type functionality is not on the horizon for Java.


For basic functional collections, Java 8 has it built in, most of the major non-Java JVM languages have it built in (Scala, Clojure, etc), and you can get add on libs for earlier Java versions.

For full language integrated access to a SQL database, Scala (runs on the JVM) has Slick


There was the programming language Pizza (a Java extension) and you should have a look to it. - It uses the concept of "fluent interfaces" to query data in a declarative manner and that is in principle identical to LINQ w/o query expressions (http://en.wikipedia.org/wiki/Pizza_programming_language). But alas it was not pursued, but it would have been one way to get something similar to LINQ into Java.


Shameless self plug: you could always use https://github.com/amoerie/jstreams

Works on Java 6 and up, a perfect fit for Android development.

It looks a lot like Scala operators, lodash, C# LINQ, etc.


Check out tiny-q. (Note that you currently can't download it.)

Here's an example adapted the above link:

First we need a collection of some data, let's say a set of strings

String[] strings = { "bla", "mla", "bura", "bala", "mura", "buma" };

Now we want to select only the strings which start with "b":

Query<String> stringsStartingWithB = new Query<String>(strings).where(
    new Query.Func<String, Boolean>(){
        public Boolean run(String in) {
            return in.startsWith("b");
        }
    }
);

No actual data moved copied or anything like that, it will get processed as soon as you start iterating:

for(String string : stringsStartingWithB ) {
    System.out.println(string);
}

As on 2014, I can finally say that LINQ is finally there in java 8.So no need to find an alternative of LINQ anymore.


There is no such feature in java. By using the other API you will get this feature. Like suppose we have a animal Object containing name and id. We have list object having animal objects. Now if we want to get the all the animal name which contains 'o' from list object. we can write the following query

from(animals).where("getName", contains("o")).all();

Above Query statement will list of the animals which contains 'o' alphabet in their name. More information please go through following blog. http://javaworldwide.blogspot.in/2012/09/linq-in-java.html


HQL (Hibernate Query Language) is very similar to Linq in .Net


You can use Java Functional Utils to convert C#'s 101 LINQ examples that's compatible with Java 1.7 on Android.


An anonymous user mentioned another one, Diting:

Diting is a class library provides query capabilities on collections through chainable methods and anonymous interface like Linq in .NET. Unlike most of other collection library those are using static methods need iterate whole collection, Diting provides a core Enumerable class whitch contains deffered chainable methods to implement query on collection or array.

Supported Methods: any, cast, contact, contains, count, distinct, elementAt, except, first, firstOrDefault, groupBy, interset, join, last, lastOrDefault, ofType, orderBy, orderByDescending, reverse, select, selectMany, single, singleOrDefault, skip, skipWhile, take, takeWhile, toArray, toArrayList, union, where


you can use scala, it is similar in syntax and it's actually probably more powerful than linq.


Maybe not the answer you're hoping for, but if some part of you code need heavy work on collections (searching, sorting, filtering, transformations, analysis) you may take in consideration to write some classes in Clojure or Scala.

Because of their functional nature, working with collections is what they're best at. I don't have much experience with Scala, but with Clojure you'd probably find a more powerful Linq at your fingertips and once compiled, the classes you'd produce would integrate seamlessy with the rest of the code base.


See SBQL4J. It's type-safe strong query language integrated with Java. Allows to write complicated and multiply nested queries. There is a lot of operators, Java methods can be invoked inside queries so as constructors. Queries are translated to pure Java code (there is no reflection at runtime) so execution is very fast.

EDIT: Well, so far SBQL4J it's the ONLY extension to Java language which gives query capabilities similar to LINQ. There are some interesting project like Quaere and JaQue but they are only API's, not syntax / semantics extension with strong type safety in compile time.


Just to add another alternative: Java 6 does have a solution for type-safe database queries using the javax.persistence.criteria package.

Though i must say that this is not really LINQ, because with LINQ you can query any IEnumerable.


Not really a "Linq to SQL" equivalent for Java. but something close to it . Query DSL


You can try out my library CollectionsQuery. It allows to run LINQ like queries over collections of objects. You have to pass predicate, just like in LINQ. If you are using java6/7 than you have to use old syntax with Interfaces:

List<String> names = Queryable.from(people)
                                    .filter(new Predicate<Person>() {
                                                public boolean filter(Person p) {
                                                    return p.age>20;
                                                }
                                            })
                                    .map   (new Converter<Person,String>() {
                                                public Integer convert(Person p) {
                                                    return p.name;
                                                }
                                            })
                                    .toList();

You can also use it in Java8, or in old java with RetroLambda and it's gradle plugin, then you will have new fancy syntax:

List<String> names = Queryable.from(people)
                                    .filter(p->p.age>20)
                                    .map   (p->p.name)
                                    .toList();

If you need to run DB queryes, than you can look on JINQ, as mentioned above, but it can't be back-ported by RetroLambda, doe to use of serialized lambdas.


For LINQ (LINQ to Objects), Java 8 will have something equivalent, see Project Lambda.

It has Enumerable's LINQ to Objects extensions like stuffs. But for more complicated LINQ things like Expression and ExpressionTree (these are needed for LINQ to SQL and other LINQ providers if they want provide something optimized and real), there is not any equivalent yet but maybe we will see that in future :)

But I don't think there will be anything like declaratives queries on Java in future.


Now that Java 8 supports lambdas, it's possible to create Java APIs that closely resemble LINQ.

Jinq is one of these new LINQ-style libraries for Java.

I am the developer of this library. It is based on five years of research on using bytecode analysis to translate Java to database queries. Similar to how C#'s D-LINQ is a query layer that sits on top of the Entity Framework, Jinq is able to act as a query layer sitting on top of JPA or jOOQ. It has support for aggregation, groups, and subqueries. Even Erik Meijer (the creator of LINQ) has acknowledged Jinq.