Introduction
In Java, there are instances when we have to have two things in one. An instance is: the name of a student and their roll number or the name of a product and the price of it. So, instead of defining a separate class each time, Java offers a simple solution a so-called Pair class. We can use it so that we do not need to write any additional code to group two associated objects.The javafx.util.Pair class is a convenient possibility to work with such pairs.

Within this article we will speak about the ways given by this class, the accessing of the values, other methods of an implementation of pairs, and why we may use Pair class as a useful tool in programming.
Methods provided by javafx.util.Pair Class
JAVA The Java programming language uses the Pair class (in the javafx.util) as a basic method of storing two values in one. It also brings beneficial ways of using these pairs. We will look at them one by one.
1. Constructor: Pair<K, V>
To make a Pair, all you have to do is to feed it with two arguments, the first one is known as the key, and the second one is the value.
Example:
import javafx.util.Pair;
public class Main {
public static void main(String[] args) {
// Creating a Pair of String & Integer
Pair<String, Integer> student = new Pair<>("Rahul", 25);
System.out.println("Pair: " + student);
}
}
Output:
Pair: Rahul=25
Here, "Rahul" is the key, and 25 is the value.
2. getKey() & getValue()
These methods retrieve the first & second elements of the pair.
Example:
Pair<String, Double> product = new Pair<>("Laptop", 599.99);
String name = product.getKey();
double price = product.getValue();
System.out.println("Product: " + name);
System.out.println("Price: $" + price);
Output:
Product: Laptop
Price: $599.99 3. equals(Object obj)
Checks if two pairs are equal (both key & value must match).
Example:
Pair<Integer, String> pair1 = new Pair<>(1, "One");
Pair<Integer, String> pair2 = new Pair<>(1, "One");
Pair<Integer, String> pair3 = new Pair<>(2, "Two");
System.out.println(pair1.equals(pair2)); // true
System.out.println(pair1.equals(pair3)); // false 4. hashCode()
Returns a unique hash code for the pair (useful in HashMaps & HashSets).
Example:
System.out.println(pair1.hashCode());
System.out.println(pair2.hashCode()); // Same as pair1
System.out.println(pair3.hashCode()); // Different 5. toString()
Converts the pair into a readable string format (key=value).
Example:
System.out.println(pair1.toString()); // Output: 1=One



