关于后端:linq-入门介绍更加优雅的流式集合处理

7次阅读

共计 1381 个字符,预计需要花费 4 分钟才能阅读完成。

拓展浏览

linq

querydsl

LINQ

术语“LINQ to Objects”指间接将 LINQ 查问与任何 IEnumerable<T> 汇合一起应用。

能够应用 LINQ 来查问任何可枚举的汇合,例如 Primitive Array、Object Array、List、Collection 或 Iterable 等等。

该汇合能够是用户定义的汇合,也能够是由 Java 开发包 API 返回的汇合。

从根本上说,“LINQ to Objects”示意一种新的解决汇合的办法。采纳 LINQ 办法,只需编写形容要检索的内容的申明性代码。

个性

  • 实现了 LINQ to Objects 的所有 API。
  • 反对更多 API 和元组。
  • 反对 IEnumerable 和 Stream 相互转换。
  • 反对 Android。

入门例子

Maven

<dependency>
    <groupId>com.bestvike</groupId>
    <artifactId>linq</artifactId>
    <version>6.0.0</version>
</dependency>

用法

如果应用 java 8 或 java 9,倡议用 lombok.var 或 lombok.val 代替简单的返回类型。

如果应用 java 10 或更高版本,倡议应用 var 代替简单的返回类型。

拼接不为空的字符串。

String result = Linq.of("!@#$%^", "C", "AAA", "","Calling Twice","SoS", Empty)
        .where(x -> x != null && x.length() > 0)
        .aggregate((x, y) -> x + "," + y);

System.out.println(result);


----
!@#$%^, C, AAA, Calling Twice, SoS

判断所有的负数是否全副为偶数。

boolean result = Linq.of(9999, 0, 888, -1, 66, -777, 1, 2, -12345)
        .where(x -> x > 0)
        .all(x -> x % 2 == 0);

System.out.println(result);
----
false

判断所有的负数是否存在任一偶数。

boolean result = Linq.of(9999, 0, 888, -1, 66, -777, 1, 2, -12345)
        .where(x -> x > 0)
        .any(x -> x % 2 == 0);

System.out.println(result);
----
true

在开端追加一个数字并在头部插入两个数字。

String result = Linq.range(3, 2).append(5).prepend(2).prepend(1).format();

System.out.println(result);
----
[1, 2, 3, 4, 5]

计算整数序列的平均值。

double result = Linq.of(5, -10, 15, 40, 28).averageInt();

System.out.println(result);
----
15.6

连贯两个整数序列。

String result = Linq.of(1, 2).concat(Linq.of(3, 4)).format();

System.out.println(result);
----
[1, 2, 3, 4]

参考资料

https://github.com/timandy/linq

本文由博客一文多发平台 OpenWrite 公布!

正文完
 0