The collections framework is a core part of the Java platform yet often misunderstood or misused by developers. The framework contains plenty of functionality for working with and manipulating collections of objects. Often though, you may want to perform an operation on a collection of objects which isn't naively supported by the framework. In such cases you end up having to code the solution into your function or hand roll your own utility to perform the generic operation.
The Jakarta Commons Collections project is a dependency found in many projects. If your using a major framework in your project, such as Spring or Struts then you'll find this dependency in your build. Commons Collections is a very under used framework considering the wealth of functionality it provides and something I think developers should make more use of instead of coding their own solutions to common challenges.
In this post I will demonstrate the use of a predicate to filter a collection of objects. Something which would be easy to code by using elements of the core Java framework but even easier to accomplish in one line with Commons Collections.
Let's start with a requirement: I have a collection of Fruit instances, the Fruit contains a field which defines the type of fruit it is and I want to filter that collection based on type. Here's my simple Fruit class:
I'm using the commons-collections4 framework which makes use of generics. Here's my build dependency:
Now we create a Predicate which will be used to evaluate the instances of Fruit in our collection and return a boolean based on the function we implement. My function is simply going to check the type of the given Fruit instance is equal to that of the predefined type I set when instantiating the Predicate implementation. I'm not going to be strict, I'm just going to check equality without regarding case sensitivity.
Note that I'm returning false if the type value is null, even though the only constructor in the Fruit class enforces that value is set it is best to be safe and I don't want any null Fruit type instances in my results. Now I can use my FruitPredicate in my logic and perform operations on collections of Fruit instances. First, we'll look at a basic function to filter the collection for a specific type of Fruit:
We can also use the same Predicate to select the inverse:
The collection returned from our select functions, which filtered for specific types of fruit, is still modifiable and we can add another Fruit of any type after the filtering has occurred. Another useful utility allows us to predicate the result preventing other types of Fruit being added after the filtering has occurred.
There's a whole host of functions which you can play around with and undoubtedly find use for in your code.
No comments:
Post a Comment