Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Pairs in Java

Pairs, as the name suggests, are a way of storing paired data. Paired data consists of two fields - one for the key and another for the value. Pairs are a great way of returning multiple values from a method. In this tutorial, we will learn different ways of using pairs in Java.

Pairs in Java

Using Pair Class of javafx.util Package

The javafx.util package has a convenient Pair class that can be used to work with pairs. We can initialize an object of this class by using the following syntax.

Pair<Key Type, Value Type> pairName = new Pair<>(key, value);

This class provides the getKey() and getValue() methods to fetch the data from the pair. The following code shows the working of these methods.

import javafx.util.Pair;
public class PairsInJava
{
	public static void main(String[] args)
	{
		Pair<String, Double> studentNameGPAPair1 = new Pair<>("Justin", 8.76);
		Pair<String, Double> studentNameGPAPair2 = new Pair<>("Jessica", 8.76);
		
		System.out.println("The Pair is: " + studentNameGPAPair1.toString());
		System.out.println("The Key is: " + studentNameGPAPair1.getKey());
		System.out.println("The Value is: " + studentNameGPAPair1.getValue());
	}
}


The Pair is: Justin=8.76
The Key is: Justin
The Value is: 8.76

Using the AbstractMap.SimpleEntry Class

The AbstractMap.SimpleEntry class in Java can be used to create a pair. Unlike the Pair class of javafx.util, this class provides the setValue() method that can be used to change the Pair's value. However, we cannot modify the key.

import java.util.AbstractMap;
public class PairsInJava
{
	public static void main(String[] args)
	{
		AbstractMap.SimpleEntry<String, Double> pair = new AbstractMap.SimpleEntry<>("Justin", 8.78);
		System.out.println("Key = " + pair.getKey() + " Value = " + pair.getValue());
		pair.setValue(8.8);
		System.out.println("Key = " + pair.getKey() + " Updated Value = " + pair.getValue());
	}
}


Key = Justin Value = 8.78
Key = Justin Updated Value = 8.8

Using AbstractMap.SimpleImmutableEntry

The SimpleImmutatedEntry class is very similar to the SimpleEntry class. The only difference is that the objects of this class are immutable. We cannot use the setValue() method for this class. We will get an UnsupportedOperationException if we use this method.

In the code below, the first two lines execute, but we get an error when we try to modify the value.

import java.util.AbstractMap;

public class PairsInJava
{
	public static void main(String[] args)
	{
		AbstractMap.SimpleImmutableEntry<String, Double> pair = new AbstractMap.SimpleImmutableEntry<>("Justin", 8.78);
		System.out.println("Key = " + pair.getKey() + " Value = " + pair.getValue());
		pair.setValue(8.8);//error
	}
}


Key = Justin Value = 8.78
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.AbstractMap$SimpleImmutableEntry.setValue(AbstractMap.java:800)
at PairsInJava.main(PairsInJava.java:9)

Using Apache Commons Library

The Apache Commons library provides us with a MutablePair class and an ImmutablePair class. Both these classes have standard getter methods to fetch the key and the value of the pair.

import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.MutablePair;
public class PairsInJava
{
	public static void main(String[] args)
	{
		MutablePair<String, Double> studentNameGPAPair1 = new MutablePair<>("Justin", 8.76);
		ImmutablePair<String, Double> studentNameGPAPair2 = new ImmutablePair<>("Jessica", 8.13);

		System.out.println("The MutablePair Key is: " + studentNameGPAPair1.getKey());
		System.out.println("The MutablePair Value is: " + studentNameGPAPair1.getValue());
		System.out.println("The ImmutablePair Key is: " + studentNameGPAPair2.getKey());
		System.out.println("The ImmutablePair Value is: " + studentNameGPAPair2.getValue());
	}
}


The MutablePair Key is: Justin
The MutablePair Value is: 8.76
The ImmutablePair Key is: Jessica
The ImmutablePair Value is: 8.13

The ImmutablePair class does not have setter methods because it creates an immutable pair that can't be modified after creation. But we have the setLeft() and setRight() methods for the MutablePair class. The setLeft() method sets the left element or the key of the pair. The setRight() method sets the right element or the value of the pair.

import org.apache.commons.lang3.tuple.MutablePair;
public class PairsInJava
{
	public static void main(String[] args)
	{
		MutablePair<String, Double> studentNameGPAPair = new MutablePair<>("Justin", 8.76);
		System.out.println("Pair before using setters: " + studentNameGPAPair.toString());
		studentNameGPAPair.setLeft("Jessica");
		studentNameGPAPair.setRight(8.13);
		System.out.println("Pair After using setters: " + studentNameGPAPair.toString());
	}
}


Pair before using setters: (Justin,8.76)
Pair After using setters: (Jessica,8.13)

Using javatuples Pair Class

The javatuples library provides different classes to implement immutable tuples in Java. The Pair class of this library can be used to create a tuple of two elements. We have the getValue() and getValueX() methods( where X denotes the index) to fetch the pair elements by index. We usually store the key at index 0 and the value at index 1. We need to use casting with the getValue() method.

import org.javatuples.Pair;
public class PairDemo
{
	public static void main(String[] args)
	{
		Pair<String, Double> studentNameGPAPair1 = Pair.with("Justin", 8.76);
		Pair<String, Double> studentNameGPAPair2 = Pair.with("Jessica", 8.13);
		
		String key1 = studentNameGPAPair1.getValue0();
		Double value1 = studentNameGPAPair1.getValue1();
		  
        //casting     
		String key2 = (String) studentNameGPAPair2.getValue(0);
		Double value2 = (Double) studentNameGPAPair2.getValue(1);
		
		System.out.println("Key-1 " + key1 + " Value-1 " + value1);
		System.out.println("Key-2 " + key2 + " Value-2 " + value2);
	}
}


Key-1 Justin Value-1 8.76
Key-2 Jessica Value-2 8.13

We also have a setAtX() method which will not alter the original pair but will return a new pair with the changes.

import org.javatuples.Pair;
public class PairDemo
{
	public static void main(String[] args)
	{
		Pair<String, Double> studentNameGPAPair1 = Pair.with("Justin", 8.76);
		Pair<String, Double> studentNameGPAPair2 = studentNameGPAPair1.setAt1(8.80);
		
		System.out.println("Original Pair: " + studentNameGPAPair1);
		System.out.println("Modified Pair: " + studentNameGPAPair2);
	}
}


Original Pair: [Justin, 8.76]
Modified Pair: [Justin, 8.8]

Using Vavr Library's Tuple2 Class

The Vavr library's Tuple2 class can be used to create an immutable pair. We can use the _1() method to fetch the key. Similarly, the _2() method can be used to fetch the value from the pair.

import io.vavr.Tuple2;

public class PairsInJava
{
	public static void main(String[] args)
	{
		Tuple2<String, Double> studentNameGPA = new Tuple2<>("Justin", 8.78);
		String key = studentNameGPA._1();
		Double value = studentNameGPA._2();
		System.out.println("Key = " + key);
		System.out.println("Value = " + value);
	}
}


Key = Justin
Value = 8.78

We also have update1() and update2() methods that return a new tuple2 object with the updates. Note that the original pair will not be altered by these methods.

import io.vavr.Tuple2;
public class PairsInJava
{
	public static void main(String[] args)
	{
		Tuple2<String, Double> studentNameGPA1 = new Tuple2<>("Justin", 8.78);
		Tuple2<String, Double> studentNameGPA2 = studentNameGPA1.update2(8.80);
		
		System.out.println("Original pair: " + studentNameGPA1);
		System.out.println("Modified pair: " + studentNameGPA2);
	}
}


Original pair: (Justin, 8.78)
Modified pair: (Justin, 8.8)

User-Defined Pair Class

If we don't want to use external libraries, then we can implement our own custom class to create pairs. It will have two member variables of the required data type. We will also add the getter and setter methods. We can create additional methods according to our requirements.

class Pair
{
	private String name;
	private Double gpa;
	
	Pair(String name, Double gpa)
	{
		this.name = name;
		this.gpa = gpa;
	}
	public String getKey() 
	{
		return name;
	}
	public void setKey(String name) 
	{
		this.name = name;
	}
	public Double getValue() 
	{
		return gpa;
	}
	public void setValue(Double gpa) 
	{
		this.gpa = gpa;
	}
}
public class PairsInJava
{
	public static void main(String[] args)
	{
		Pair studentNameGPA = new Pair("Justin", 8.76);
		System.out.println("Key: " + studentNameGPA.getKey());
		System.out.println("Value: " + studentNameGPA.getValue());		
		studentNameGPA.setValue(8.80);
		System.out.println("New Value: " + studentNameGPA.getValue());
	}
}


Key: Justin
Value: 8.76
New Value: 8.8

Using Object Arrays To Create Pairs in Java

Another alternative to external libraries is to use an array of Objects. Since all classes extend the Object class, we can easily store any class object in this array.

public class PairsInJava
{
	public static void main(String[] args)
	{
		String key = "Justin";
		Double value = 8.78;

		Object[] objArr = new Object[2];
		objArr[0] = key;
		objArr[1] = value;
		
		System.out.println("Key = " + objArr[0]);
		System.out.println("Value = " + objArr[1]);
	}
}


Key = Justin
Value = 8.78

Summary

Pairs are a simple way to store two data items that have a mapping between them. Pairs usually store a key and its corresponding value. There are plenty of ways of using Pairs in Java. We can use external libraries like Apache Commons or the Vavr library to implement pairs. We can also define our own pair class which can have additional methods to serve our needs.