47

LINQ for Java (functional builders like jOOQ or QueryDSL)

 5 years ago
source link: https://www.tuicool.com/articles/hit/QJzau27
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JINQ

Java IN tegrated Q uery in parlance with LINQ is an ultra minimalistic library for Java inspired from and mimicking the .NET LINQ . While LINQ is a language construct, JINQ is composed of types - classes and methods, but to the same effect.

JINQ allows you to rewrite conventional and nested loop based data processing code into query oriented and highly readable code.

Here is a typical loop based data processing code:

List<ProductDisplayInfo> getDisplayList(Product[] products) {
	List<ProductDisplayInfo> pdiList = new ArrayList<>();

	for (int index = 0; index < products.length; ++index) {
		Product p = products[index];

		if (product.getCategory() == 2 || product.getCategory() == 5) {
			boolean yes = isProductUnderDiscount(product);

			if (!yes) {
				ProductDisplayInfo pdi = new ProductDisplayInfo();
				// whatever you want to populate pdi with ...

				pdiList.add(pdi);
			}
		}
	}

	return pdiList;
}

Here is a C# LINQ snippet:

var query = from p in products
	where p.getCategory == 2 || p.getCategory == 5 && isProductUnderDiscount(p)
	select new ProductDisplayInfo(p);

var pdiList = query.ToList();

Here is JINQ in action:

final Iterable<ProductDisplayInfo> query = new Enumerable<>(products)
	.where(p -> p.getCategory == 2 || p.getCategory == 5 && isProductUnderDiscount(p))
	.select(p -> { new ProductDisplayInfo(p); } ); // or select(ProductDisplayInfo::new);

final List<ProductDisplayInfo> pdiList = query.toList();

or

for (ProductDisplayInfo pdi : pdiList) {
	System.out.println(pdi);
}

Elaboration of JINQ is in progress. Until then you can try the related blog post .


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK