A mutable pair consists of two object elements.
MutablePair
is defined in the Apache Commons Lang. The package has to be added to the classpath before MutablePair
is used.
If Maven is used, add the following in the dependencies
section of pom.xml
.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
After the dependency above is imported, import the MutablePair
class as follows.
import org.apache.commons.lang3.tuple.MutablePair;
Note: There are setters in this class, as the data structure is mutable in nature.
The two object elements in the MutablePair
are named left
and right
. Therefore, the objects will be referred to as left
and right
for any operations on the data structure.
MutablePair
objectThere are several ways to create a MutablePair
object.
The constructor of the MutablePair
class accepts the left
and right
elements as parameters.
MutablePair<String, String> mutablePair = new MutablePair<>("leftValue", "rightValue");
The of(left, right)
method can be used to create an object of the MutablePair
class. It accepts the left
and right
elements as parameters.
MutablePair<String, String> mutablePair = MutablePair.of("leftValue", "rightValue");
MutablePair
objectleft
elementThe value of the left
element can be set using the setLeft()
method.
mutablePair.setLeft("leftValue");
right
elementThe value of the right element can be set using the setRight()
method.
mutablePair.setRight("rightValue");
MutablePair
objectleft
elementThe left
element can be accessed as a property or by the getLeft()
method.
String leftElement = mutablePair.left;
// OR
String leftElement = mutablePair.getLeft();
right
elementThe right
element can be accessed as a property or by the getRight()
method.
String rightElement = mutablePair.right;
// OR
String rightElement = mutablePair.getRight();
In the example below, a MutablePair
object is created without the left
and right
values. Then, the elements of the object are set using the setters, and the elements are printed using the getters.
import org.apache.commons.lang3.tuple.MutablePair;public class Main {public static void main(String[] args){MutablePair<String, String> mutablePair = new MutablePair<>();mutablePair.setLeft("leftValue");mutablePair.setRight("rightValue");System.out.println("Left Element - " + mutablePair.getLeft());System.out.println("Right Element - " + mutablePair.getRight());}}