Coder Social home page Coder Social logo

linq's Introduction

Linq.J A Memory-based Object Query language

中文 / English

Java uses Linq capabilities similar to C# C# Linq

Erupt Framework maven-central jdk 8+ license Apache 2.0 GitEE star GitHub stars

Linq is Object oriented sql, linq is actually a query on the data in memory, enabling developers to write queries more easily. These query expressions look a lot like SQL

You can join, filter, sort, and group data sources with minimal code. These operations can be combined in a single query to obtain more complex results

allows you to write Java code that manipulates in-memory data in the same way that you query a database, for example

  • List, Array
  • SQL result data
  • CSV, XML, JSON document datasets
  • Stream, File stream

Application Scenarios

  • Result association for RPCS such as Feign/Dubbo during distributed development
  • In-memory computation of heterogeneous system data
  • Use code to organize SQL result data
  • Sorted aggregation of multiple result objects with in-memory paging
  • Semantic object transformation and mapping
  • Clean code, no need for loops and branches to manipulate data
  • Federated access across data sources

Operation syntax

From Select DistinctJoinWhereGroup ByOrder ByLimitOffset...

Tips

⚠️ Note: The object field must have a get method to facilitate lambda lookup. It is recommended to use the Lombok @Getter annotation to quickly create get access to the field

How to Use

It has zero external dependencies and is only 50kb in size

<dependency>
    <groupId>xyz.erupt</groupId>
    <artifactId>linq.j</artifactId>
    <version>0.0.4</version>
</dependency>

Example 1

var strings = Linq.from("C", "A", "B", "B").gt(Th::is, "A").orderByDesc(Th::is).write(String.class);
// [C, B, B]

var integers = Linq.from(1, 2, 3, 7, 6, 5).orderBy(Th::is).write(Integer.class);
// [1, 2, 3, 5, 6, 7]

var name = Linq.from(data)
    // left join
    .innerJoin(target, Target::getId, Data::getId)
    // where like
    .like(Data::getName, "a")
    // select name
    .select(Data::getName)
    // distinct
    .distinct()
    // order by 
    .orderBy(Data::getName)
    .write(String.class);

Example 2

public class ObjectQuery{

    private final List<TestSource> source = http.get("https://gw.alipayobjects.com/os/antfincdn/v6MvZBUBsQ/column-data.json");

    private final List<TestSourceExt> target = mongodb.query("db.target.find()");
    
    /**
     * select demo
     */
    public void select(){
        // select *
        Linq.from(source).select(Columns.all(TestSource.class));
        // select a, b, c
        Linq.from(source)
                .select(TestSource::getName, TestSource::getDate, TestSource::getTags)
                .select(Columns.of(TestSource::getTags, "tag2")) // alias
                .select(Columns.ofx(TestSource::getId, id -> id + "xxx")); // value convert
        // select count(*), sum(id), max(id) 
        Linq.from(source)
                .select(Columns.count("count"))
                .select(Columns.sum(TestSource::getId, "sum"))
                .select(Columns.max(TestSource::getId, "max"));
    }

    
    /**
     * join demo
     */
    public void join(){
        // left join
        Linq.from(source).leftJoin(target, TestSourceExt::getId, TestSource::getId).select(
            Columns.all(TestSource.class),
            Columns.of(TestSourceExt::getName),
            Columns.of(TestSourceExt2::getValue)
        );
        // right join
        Linq.from(source).rightJoin(target, TestSourceExt::getId, TestSource::getId);
        // inner join
        Linq.from(source).innerJoin(target, TestSourceExt::getId, TestSource::getId);
        // full join
        Linq.from(source).fullJoin(target, TestSourceExt::getId, TestSource::getId);
    }

    
    /**
     * where demo
     */
    public void where() {
        // =
        Linq.from(source).eq(TestSource::getName, "Thanos").select(Columns.count(countAlias)).writeOne(Integer.class);
        // >=:lval and <=:rval
        Linq.from(source).between(TestSource::getId, 1, 3);
        // in (x,x,x)
        Linq.from(source).in(TestSource::getId, 1, 2, 3);
        // like '%x%'
        Linq.from(source).like(TestSource::getName, "a");
        // is null
        Linq.from(source).isNull(TestSource::getId);
        
        // customer single field where
        Linq.from(source).where(TestSource::getId, id -> id >= 5);
        
        // customer condition or multi field
        Linq.from(source).condition(data -> {
            String name = data.get(TestSource::getName);
            Integer age = (Integer)data.get(TestSource::getAge);
            // name = 'xxx' or age > 10
            return "xxx".equals(name) || age > 10;
        });
    }

    
    /**
     * group by demo
     */
    public void groupBy(){
        Linq.from(source)
            .groupBy(TestSource::getName)
            .select(
                Columns.of(TestSource::getName, "name"),
                Columns.min(TestSource::getDate, "min"),
                Columns.avg(TestSource::getId, "avg"),
                Columns.count("count"),
                Columns.count(TestSource::getName, "countName"),
                Columns.countDistinct(TestSource::getName, "countDistinct")
            )
            .having(row -> Integer.parseInt(row.get("avg").toString()) > 2)
            .orderBy(TestSource::getAge);
    }

    
    /**
     * result write demo
     */
    public void write(){
        // write List<Object>
        List<TestSource> list = Linq.from(source).orderByAsc(TestSource::getDate).write(TestSource.class);
        // write Object
        TestSource obj = Linq.from(source).limit(3).writeOne(TestSource.class);
        // write List<Map>
        List<Map<String, Object>> map = Linq.from(source).writeMap();
        // write Map
        Map<String, Object> mapOne = Linq.from(source).writeMapOne();
    }
    
}

Next iteration plan

  • Supports combining multiple query result sets: UNION ALL, UNION, INTERSECT, EXCEPT, UNION BY NAME
  • Supports window functions
  • Support Nested loop join
  • supports having
  • Support group column format group by date(created_at)

linq's People

Contributors

erupts avatar

Stargazers

 avatar Aurthur avatar 616 avatar Taketoday avatar  avatar  avatar  avatar 汪小哥 avatar  avatar

Watchers

 avatar

Forkers

bravet

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.