Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
immutable pair
pair
communitycreator

What is an ImmutablePair in Java?

abhilash

Overview

An immutable pair consists of two object elements.

Though the implementation is immutable, there is no restriction on the objects that can be stored. If mutable objects are stored in the pair, then it effectively becomes mutable.

ImmutablePair is defined in the Apache Commons Lang. The package has to be added to the classpath before using ImmutablePair.

If using Maven, 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 importing the above dependency, import the ImmutablePair class as follows:

import org.apache.commons.lang3.tuple.ImmutablePair;

Note: There are no setters in this class, as the data structure is immutable in nature.

The two object elements in the ImmutablePair are named left and right. Therefore, the objects will be referred to as left and right for any operations on the data structure.

Create an ImmutablePair object

There are several ways to create an ImmutablePair object.

  1. Using the constructors:

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

ImmutablePair<String, String> immutablePair =  new ImmutablePair<>("leftValue", "rightValue");
  1. Using of() method:

The of(left, right) method can be used to create an object of the ImmutablePair class. It accepts the left and right elements as parameters.

ImmutablePair<String, String> immutablePair =  ImmutablePair.of("leftValue", "rightValue");

Access the elements of ImmutablePair object

Accessing the left element

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

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

Accessing right element

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

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

Example

In the example below, an ImmutablePair object is created with the left and right values. Then, the elements of the object are printed.

import org.apache.commons.lang3.tuple.ImmutablePair;

public class Main {

    public static void main(String args[])
    {
        ImmutablePair<String, String> immutablePair =  ImmutablePair.of("leftValue", "rightValue");
        System.out.println("Left Element - " + immutablePair.getLeft());
        System.out.println("Right Element - " + immutablePair.getRight());

    }
}

RELATED TAGS

java
immutable pair
pair
communitycreator
RELATED COURSES

View all Courses

Keep Exploring