Java Pair3 May 2025 | 9 min read Pairs are useful when we want two values to be returned from a method. For example, if we have a method that calculates the square root of a number and we want to print the number with its square root, we can use the Pair class to print the output as a combination of numbers and their square roots (for example, (5, 25)). Java provides an inbuilt Pair class from Java 8. In this section, we will see how to use the Pair class in Java. Further, we will create our customized Pair class. The ability to handle various kinds of data pairs and operations is made possible by this customisation. Developers can customize functionality, like adding extra methods or restrictions, to enable more precise control over the key-value pairs by implementing a custom Pair class. This method improves overall data structure handling efficiency, readability, and maintainability of the code. Pair Class in JavaSince Java 8, Java provides a Pair class to store the values in key pair combinations. To store the value in pair combination, we need to use the parameterized constructor provided by the javafx.util.Pair class. The Pair class is useful while storing the value in a tree data structure. While performing the recursion operation on a tree data structure, it is easy to pass value from one node to another node using the Pair class. These values can be minimum and maximum node values up to that node. This would prevent the pointer from revisiting certain codes repeatedly. In Java, the Maps are used to store the value in the form of a key pair combination. They store the value as tuples and operate them as a single object. Java's Pair class provides a useful method for managing key-value pairs, making it easier to do a variety of tasks like organizing and retrieving data. Since Java 8, the javafx.util.Pair class has grown in importance as a useful tool for programmers, particularly when working with tree data structures. Developers can effectively transport values between nodes during recursive operations on trees, such as traversals and searches, by using Pair objects. This enables the smooth movement of data, such as minimum and maximum node values, between various regions of the tree, which helps to optimize efficiency and minimize redundant code execution. Furthermore, even though Java Maps are frequently used to store key-value pairs, the Pair class provides a lightweight substitute for situations where a more straightforward, targeted approach is desired-all without the complexity that comes with a full-fledged Map implementation. Developers can increase the efficiency and clarity of their algorithms and data structures, as well as streamline their code, by utilizing the capabilities of the Pair class. To implement the Pair class, we need to import its parent package: The inbuilt Pair class uses the following notation of Key and Value just like the Map in Java, to store a pair: Declaration: The Pair class object is declared as follows: The above syntax will create an object of the type <Integer, String> and the constructor will take the value 5 and "Five" and store them in the Pair class. Pair Class MethodsThe following methods are provided by the Java Pair class: getKey() It gets the key for the given pair and returns the key for the specified pair. It is declared as follows: getValue() It gets the value for the given pair and returns the value of the pair. It is declared as follows: hashCode() It generates the hash code for the pair; this hashcode is calculated using both the name and value of the pair. It overrides the HashCode class and returns the hash code for the pair. It is declared as follows: equals() It is used to test the pair for equality with the other pair. If the object is not specified for the testing or is null, then it will return false. The given two pairs will be considered as equal if and only if their names and values are the same. It is declared as follows: It takes the "-o" arguments object to test for the equality with the pair. It overrides the equals in the class Objects and returns true if the given pair is equal; otherwise, it will return false. toString() It is used to represent the pair as String. In toString() method the default name/value delimiter=' is always used. It overrides the toString in class Object and returns the String value of the pair. It is declared as follows: Pair Class ConstructorThe Pair class constructor creates a new pair. It takes the key and pair values as an argument. It is declared as follows: Types of Pair ClassesThere are two types of Pair classes in Java, which are as follows:
Why do We Need Pair Class?The Pair class is used to get the value in a key pair combination. In other terms, we can say that the pair class provides methods that return two values together. There may be lots of reasons why we use the Pair class. The following are a few cases when we need to use the Pair class:
Example of Pair ClassLet's understand it with a basic example: Pair class is a part of the JavaFX, so we need to create and configure a JavaFX project. See How to create a JavaFX project in Eclipse. Now, create a class file under the src folder. We are creating a TestPair class. TestPair.java: Output: The key is :5 The Pair value is :Five Explanation The Pair class from the JavaFX library is used in this Java code. An instance of Pair with the integer key 5 and the string value "Five" is generated in the main method. The key can be obtained from the pair using the getKey() method, while the value can be obtained using the getValue() function. Finally, System.out.println() commands are used to print these numbers. As in the preceding example, there is no need to define a special class when storing a pair of values thanks to JavaFX's Pair class. Customized Pair ClassIf we do not want to use the inbuilt Pair class, we can customize a Pair class using Generics. Consider the below example: File Name: CustomizedPair.java From the above code, we have created a Customized Pair class and store two values in a single variable and print it. Output: < 1, Hello > From the above code, we have created a Customized Pair class and store two values in a single variable and print it. Explanation This Java code introduces the CustomizedPair class. A key-value pair is represented by this class, where the value is a string (String) and the key is an integer (int). The constructor of the class initialises the instance variables with the values it receives as inputs-an integer key and a string value. Another way is print(), which uses System.out.println() to print the key-value pair in the format "< key, value >". Lastly, the print() function on an instance of CustomizedPair with key 1 and value "Hello" is used in the main method to print the pair, illustrating how to use this class. Hence, using generics methods, we can take the benefits of a Pair class without using JavaFX. Let's understand its behavior with functions. Pair Class with FunctionsWe can use a Pair class to return two values using a function. To perform this process, the return type of function must be a pair. Consider the example below: File Name:TestPair2.java Output: Enter Value Five Enter Key 5 < 5, Five > Explanation This Java code allows the user to input a key-value pair interactively via the console. It starts by importing the Scanner class from java.util package. The TestPair2 class contains a main method where it creates a Scanner object to read input from the console. It then calls the func method with the Scanner object as an argument, which prompts the user to enter a value and a key.Inside the func method, it prints a message asking the user to enter a value and then reads a string input from the user for the key using s.next(). It then prints another message asking for the key and reads an integer input from the user for the value using s.nextInt(). After obtaining both key and value, it creates a new CustomizedPair object using the provided key and value, and returns this object.Back in the main method, the returned CustomizedPair object is stored in variable a, and then the print method is called on it to print the key-value pair to the console. ConclusionIn conclusion, the Pair class in Java provides a convenient way to store key-value pairs, offering flexibility and ease of use in various scenarios. By encapsulating two values into a single entity, developers can simplify code and improve readability, especially when dealing with related data sets. Whether it's through the inbuilt javafx.util.Pair class or a custom implementation, pairs are valuable tools for returning multiple values from methods, managing data in tree structures, or simply organizing related data efficiently. Additionally, the ability to customize Pair classes allows developers to tailor functionality to specific needs, enhancing control over key-value pairs and improving overall code maintainability and efficiency. Overall, the Pair class in Java is a versatile and powerful tool that enhances the capabilities of Java programmers in handling data structures and organizing data effectively. |
Number Complement Problem in Java
The Number Complement problem is an interesting challenge that involves binary operations and bit manipulation. In this section, we will explore this problem in detail, delve into the theory behind it, and provide a comprehensive solution in Java. This problem is commonly found in coding...
5 min read
Abstraction vs Encapsulation
Abstraction Vs Encapsulation Java is an object-oriented programming language and it follows OOPs concepts. The OOPs concepts include classes, objects, polymorphism, inheritance. There are two other features of OOPs i.e. abstraction and encapsulation. They both seem very similar but totally different in concept and implementation. The major...
3 min read
DecimalStyle withDecimalSeparator() Method in Java with Examples
The java.time.format.DecimalStyle contains the DecimalSeparator() method. The character that is used to indicate the decimal separator for the Locale of this DecimalStyle is configured using the DecimalStyle class in Java. This function returns a DecimalStyle instance with the updated negative sign character when it receives the...
3 min read
Methods of Gson in Java
In Java, Gson is defined as a library which was developed by the Google for serialization and deserialization of JSON (JavaScript Object Notation). The main purpose of Gson in Java is converting objects of Java into formats of JSON and vice versa. Let's understand in detail about...
7 min read
Java Convert Array to Collection
In Java, changing an array to a collection may be finished using diverse techniques supplied by way of the Java Collections Framework. The Collections Framework presents a hard and fast of interfaces and training to manipulate collections of objects. To convert an array to a set,...
9 min read
How to Install SSL Certificate in Java
? In Java, an SSL certificate can be defined as a type of digital certificate which is utilized for providing a safe, encrypted, and secure connection between a server and a client that is using the SSL/TLS (Secure Socket Layer/ Transport Layer Security) protocols. In the fields...
5 min read
Java Throwable.setStackTrace() Method
The stack trace elements are set to the throwable object using the Throwable class's setStackTrace(StackTraceElement[] stackTrace) method. getStackTrace() returns this stack trace, and printStackTrace() and related methods print it. By using the method, a user can override the default stack trace that is either deserialized when...
4 min read
Butterfly Pattern in Java
In this section, we will understand how to create a Java program to pint the Butterfly Pattern. It is frequently asked by the interviewers to check the logical thinking of the of the candidate. In order to implement the logic for Butterfly Pattern, we take input N...
4 min read
How to Pass Integer by Reference in Java?
In Java, primitive types like int are passed by value, meaning changes made to them in methods do not affect the original value. However, by using wrapper classes, arrays, or other mutable objects like AtomicInteger or MutableInt, an integer can be passed by reference, allowing its...
5 min read
Vertical Flip Matrix Problem in Java
The problem statement for vertical flipping of a matrix involves taking a two-dimensional matrix and reversing the order of its rows, essentially flipping it vertically. Mathematically, if the original matrix is denoted as M and the vertically flipped matrix as M', the transformation can be represented...
6 min read
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India