Java Pair Class – Learn to Implement them in Java

In this Java tutorial, we will learn another highly useful programming concept that is pair class in Java. The Pair class in Java was introduced since Java 8.

We will learn how to use and implement a javafx.util.pair class in programs. We will also study various methods provided by a javafx.util.pair class.

At last, we will discuss the Java Pair Example. The javafx.util.Pair in Java is a class that stores a pair. We use the parameterized constructor of the javafx.util.Pair class, to store the values into Pair.

Pair Class in Java

A pair is a container that provides a convenient way to store a simple key to value. It stores a tuple of two objects. In Java, Maps.Entry is an excellent example that stores key-value pairs. Maps store a collection of pairs and treat them as a single unit.

The Pair class does not specify the relationship between the specified values. In C++, std::pair is similar to pair class in Java. In C++, the first and second fields can be anything.

The implementation of Pair class contains the following components:

  1. Two public fields: first and second, just like in C++.
  2. A private constructor: takes two arguments – a key and, its corresponding value.
  3. Method of(): A static factory method for creating an immutable, Typed Pair instance.
  4. Overridden methods hashCode() and equals(): These methods are used to ensure the desired behavior in hash-based collections.
  5. Overridden toString() method: This method prints the Pair object in String form.

Syntax of Constructor of the pair class:

Pair<Integer, String> pair = new Pair<>(3, "Three");
Integer key = pair.getKey();
String value = pair.getValue();

Need for Pair Class in Java

We use Pairs or Pair class in Java to return two values from a method. For example, there is a method that returns both the cube root of the number and the number itself. Therefore, we need to merge a number with its cube root in a pair.

This pair or combination may result in (number, cube root of a number). For example, (125, 5) and (216, 6).

Types of Pair Class in Java

Mutable Pair

Mutable pairs are the pairs for which we can change their data values. Through this pointer, we can call their getter and setter methods.

These methods are pair.getValue(); and pair.setValue (3, 4). The function setValue() sets the values in the pair, and getValue() returns the values from the pairs.

Immutable Pair

Immutable pairs are the pairs for which we can’t change or set the data values. Once, we set the data values in the pair, then we cannot call the pair.setValue (3, 4) method gain to change the values.

Example:

package com.techvidvan.pairclass;
public class Pair<T>
{
  T p1, p2;

  void setValue(T a, T b)
  {
    this.p1 = a;
    this.p2 = b;
  }

  Pair<T> getValue()
  {
    return this;
  }
  public static void main(String args[ ])
  {
    Pair<Integer> pair = new Pair<Integer> ( );
    pair.setValue(1,2);

    Pair <Integer> answer= new Pair <Integer>( );
    answer = pair.getValue();

    System.out.println(answer.p1 + " " + answer.p2);
  }
}

Output:

1 2

Methods of javafx.util.Pair Class

1. boolean equals()

This method compares two pair objects on the basis of the (<Key, Value>) of the pair objects.

Example to understand the equals() method of Pair class:

Pair p1 = new Pair(3,4);
Pair p2 = new Pair(3,4);
Pair p3 = new Pair(4,4);
System.out.println(p1.equals(p2));	 //prints true
System.out.println(p2.equals(p3));	 //prints false
2. String toString()

It returns the String representation of the Pair object.

3. K getKey()

It returns the key for the pair.

4. V getValue()

It returns the value for the pair.

5. int hashCode()

hashCode() method generates a hash code for the Pair.

Implementation of the javafx.util.Pair Class

package com.techvidvan.pairclass;
import java.util.ArrayList;
public class Pair<T1, T2>
{
  private String string;
  private int i;

  public Pair(String string, int i)
  {
    this.string=string;
    this.i=i;
  }

  public static Pair <String,Integer> getMaximum(ArrayList < Pair 	<String,Integer> > arrayList)
  {
    int max = Integer.MIN_VALUE;
    Pair <String, Integer> ans = new Pair <String, Integer> (" ", 0);

    for (Pair <String,Integer> temp : l)
    {
      int val = temp.getValue();
      if (val > max)
      {
        max = val; // update maximum
        ans = temp; // update the Pair
      }
    }
    return ans;
  }

  private int getValue()
  {
    return i;
  }
  private String getKey()
  {
    return string;
  }

  public static void main (String[] args)
  {
    //Create an Array List
    ArrayList <Pair <String, Integer>> arrayList = new ArrayList <> ( );
    arrayList.add(new Pair <String,Integer> ("Cricketer A", 76));
    arrayList.add(new Pair <String,Integer> ("Cricketer B", 97));
    arrayList.add(new Pair <String,Integer> ("Cricketer C", 45));
    arrayList.add(new Pair <String,Integer> ("Cricketer D", 65));
    arrayList.add(new Pair <String,Integer> (“Cricketer E", 110));

    Pair <String,Integer> answer = getMaximum(arrayList);
    System.out.println(answer.getKey() + " is the man of the match " + "with a number of runs: " + answer.getValue());
  }
}

Output:

Cricketer E is the man of the match with the number of runs: 110

Summary

Here we come to the end of our tutorial. In this article, we learned about the pair class in Java which is used for storing key-value pairs. We got to know the importance of the javafx.util.pair class along with its various types and methods associated with it.

At last, we explored how to implement pair class in Java taking real-life examples for your better understanding.

Thank you for reading our article. Do share it on Social Media.

Happy Learning 🙂