Over a million developers have joined DZone.

Manipulating Collections With a Fluent Interface

· Java Zone

Easily build powerful user management, authentication, and authorization into your web and mobile applications. Download this Forrester report on the new landscape of Customer Identity and Access Management, brought to you in partnership with Stormpath.

Lambdaj is a Java library that allows you to manipulate collections in a declarative way. In particular its API is designed to be easily combined in more complex single statements as in the following example:

List<Person> fastCarsOwnersSortedByAges = sort(
extract(
select(cars, having(on(Car.class).getSpeed(), greaterThan(200)))
), on(Car.class).getOwner()
), on(Person.class).getAge());
Here a list of Cars is filtered in order to select only the ones faster than 200 km/h. Then the owners of all of these cars are extracted and in the end the resulting Persons are sorted based on their ages. The select(), extract() and sort() methods are all static methods so they can be used with a simple static import. This single statement looks quite powerful, especially if you compare what you should do to achieve the same result in plain Java:
List<Person> fastCarsOwnersSortedByAges = new ArrayList<Person>();
for(Car car : cars) {
if (car.getSpeed() > 200) {
fastCarsOwnersSortedByAges.add(car.getOwner());
}
}
Collections.sort(fastCarsOwnersSortedByAges, new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return p1.getAge() - p2.getAge();
}
});
Anyway the lambdaj version can be a bit difficult to be read due to its nested form. That's why the release 2.3 of the library introduced the so called LambdaCollections that allows developers to use the same features in a more readable way:
List<Person> fastCarsOwnersSortedByAges = with(cars)
.retain(having(on(Car.class).getSpeed(), greaterThan(200)))
.extract(on(Car.class).getOwner())
.sort(on(Person.class).getAge());

These special collections implement a fluent interface providing a more handy way to employ lambdaj's features. In more detail, the with() static method wraps a plain list (set, map or array) with the corresponding lambda collection.

Note that the LambdaCollections actually implement the corresponding Java interface (i.e. LambdaList implements java.util.List) so you can use them in all other APIs as usual. This is done by simply delegating to the original wrapped collection for the methods belonging to the base interface, so you don't have to pay any performance penalty when invoking these methods.

Thus the LambdaCollections seamlessly enrich the API of the traditional Java Collections Framework with a fluent interface that allows you to leverage lambdaj's feature in a more comfortable way. The invocations of the methods of this fluent interface also change the state of the original wrapped collection. This implementation choice has been driven by 2 reasons:

  1. While to leave the original collection unchanged is closer to the functional programming principles, it didn't make too much sense to enforce an immutable API on an object that is however widely mutable by invoking the methods of the collection framework API.
  2. By never changing the instance of the wrapped collection assures that its characteristic are always reflected even by the wrapping lambdaj counterpart. It means, for example, that if you are wrapping a SortedSet with a LambdaSet, the items in this last Set are always guaranteed of staying sorted with the same criteria defined in the original Set.

Of course if you need to leave unchanged the original collection (i.e. when it is a list of JPA entities and you don't want to accidentally cascade delete entities from the database) it is enough to clone it before to use the other fluent methods as it follows:

with(cars).clone().remove(...) ...

The Java Zone is brought to you by Stormpath—a complete, pre-built User Management API. Want to learn how to use JWTs to protect microservices from CSRF and more? Check out this on-demand webinar with our Java Developer Evangelist, Micah Silverman.

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}