What is a MutablePair in Java?

Overview

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.

How to create a MutablePair object

There are several ways to create a MutablePair object.

Use the constructor

The constructor of the MutablePair class accepts the left and right elements as parameters.

MutablePair<String, String> mutablePair =  new MutablePair<>("leftValue", "rightValue");

Use the of() method

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");

How to set elements of the MutablePair object

Set the left element

The value of the left element can be set using the setLeft() method.

mutablePair.setLeft("leftValue");

Set the right element

The value of the right element can be set using the setRight() method.

mutablePair.setRight("rightValue");

How to access the elements of the MutablePair object

Access the left element

The left element can be accessed as a property or by the getLeft() method.

String leftElement = mutablePair.left;
// OR
String leftElement = mutablePair.getLeft();

Access the right element

The right element can be accessed as a property or by the getRight() method.

String rightElement = mutablePair.right;
// OR
String rightElement = mutablePair.getRight();

Code

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());
}
}

Free Resources