This post will discuss how to implement a Triplet class in Java that can store three values of any type, using the Pair class provided by the Apache Commons Lang library.

A Triplet class is a class that can store three objects of different types, that can be unrelated to each other. A triplet is a useful data structure but it is not included in the standard Java Development Kit (JDK). Many Java developers wish they had this class at their disposal. We have already learned how to create a custom Triplet class in Java that can store three values of any type. In this post, we will see how to use the Pair class from the Apache Commons Lang library to implement the Triplet class in a simple way. For example, one possible implementation of the Triplet class could be:

Download Code

 
The above implementation is a little verbose. Following is the simplified version that uses MutablePair class from Apache Commons Lang. which can store two mutable values. The idea is to extend the MutablePair class and add an extra field for the middle element. We also need to provide getter and setter methods for this field, as well as override the equals, hashCode, and toString methods. For instance:

Download  Run Code

That’s all about implementating Triplet class using Pair class in Java.