In C++, we have std::pair in the utility library which is of immense use if we want to keep a pair of values together. We were looking for an equivalent class for pair in Java but Pair class did not come into existence till Java 7. JavaFX 2.2 has the javafx.util.Pair class which can be used to store a pair. We need to store the values into Pair using the parameterized constructor provided by the javafx.util.Pair class.
Note : Note that the <Key, Value> pair used in HashMap/TreeMap. Here, <Key, Value> simply refers to a pair of values that are stored together.
Methods provided by the javafx.util.Pair class
- Pair (K key, V value) : Creates a new pair
- boolean equals() : It is used to compare two pair objects. It does a deep comparison, i.e., it compares on the basic of the values (<Key, Value>) which are stored in the pair objects.
Pair p1 =
Pair p2 =
Pair p3 =
System.out.println(p1.equals(p2) + “ ” + p2.equals(p3));chevron_right
- String toString() : This method will return the String representation of the Pair.
- K getKey() : It returns key for the pair.
- V getValue() : It returns value for the pair.
- int hashCode() : Generate a hash code for the Pair.
Let us have a look at the following problem.
Problem Statement : We are given names of n students with their corresponding scores obtained in a quiz. We need to find the student with maximum score in the class.
Note : You need to have Java 8 installed on your machine in order to run the below program.
Student C is top scorer with score of 99
Note: The above program might not run in an online IDE, please use an offline compiler.
This article is contributed by Chirag Agarwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Implement Triplet Class with Pair Class in Java using JavaTuples
- Implement Pair Class with Unit Class in Java using JavaTuples
- Pair Class in JavaTuples
- Implement Sextet Class from Quintet Class in Java using JavaTuples
- Implement Quintet Class with Quartet Class in Java using JavaTuples
- Implement Ennead Class from Octet Class in Java using JavaTuples
- Implement Decade Class from Ennead Class in Java using JavaTuples
- Implement Quartet Class with Triplet Class in Java using JavaTuples
- Implement Septet Class from Sextet Class in Java using JavaTuples
- Implement Octet Class from Septet Class in Java using JavaTuples
- In Java, Can we call the main() method of a class from another class?
- Difference between Abstract Class and Concrete Class in Java
- Using predefined class name as Class or Variable name in Java
- Java.lang.Class class in Java | Set 2
- Java.lang.Class class in Java | Set 1