Pair Class in Java with Examples
One of the most significant concepts in Java is the pair class. It was not available in Java until Java 7. This class exists only since Java 8. It enables the programmers to store data in the form of pairs. This article explains about implementing javafx.util.pair class and its functionalities.
What is a pair class in Java?
The concept pair in Java lets us store simple key values in a suitable way. In simple words, it is a container to hold these pair values. The pair class in Java is present within the util package of the JavaVFX package.
In Java, Maps.Entry is the best example that stores key-value pairs. Here, maps store a collection of pairs and they are considered as a single unit. This class does not mention the relationship between the given values. In C++, std::pair is related to the pair class in Java.
Implementation of Java Pair class
Pair class implementation in java contains the below components:
1. There are two public fields: first and second as in C++.
2. It consists of a private constructor and takes a couple of arguments, a key, and its, corresponding value.
- Method of(): It is a static factory method that lets us creates an immutable, Typed Pair instance.
- Overridden methods hashCode() and equal(): It guarantees the desired behavior in hash-based collections.
- Overridden toString() method: It prints the Pair object on String form.
3. To implement the Pair class, we must import its parent package too:
import javafx.util.Pair;
4. The inbuilt pair class requires the given notation of Key and Value like the Map in Java to store a pair.
<Key, Value>
Importing a Pair class in Java:
You can import a pair class in the given way:
import javafx.util.Pair;
Declaration of Java Pair class object:
Pair<Integer, String> p = new Pair<>(2, “Two”);
This line will create an Integer object and the constructor will obtain the values 2 and “Two” to store in the Pair class.
Accessing Values from Java Pair class:
To access the values, we use the getKey() method to attain the first value and the getValue() method to attain the second value. These methods are briefly explained later in this article.
To have an idea, here is a sample program to show these methods work:
import javafx.util.Pair; public class FirstCodePairSample{ public static void main(String[] args) { Pair<Integer, String> p = new Pair<>(4,"FirstCode"); System.out.println("The first value is :" + p.getKey()); System.out.println("The second value is :" + p.getValue()); } }
Output:
The first value is: 4The second value is: FirstCode
Process finished with exit code 0
Pair class Methods in Java:
1. Pair (K key, V value)
It creates a new pair and assigns two values to the Pair class.
2. getKey()
It attains the key for the given pair and returns the key for the mentioned pair. We can declare it as:
public K getKey()
3. getValue()
It obtains the value for the given pair and returns the value of the pair. We can declare it as:
public V getValue()
4. hashCode()
It generates the hash code for the pair. It is calculated using the name and the value of the pair. This method overrides the HashCode class and returns the hash code for the pair. we can declare it as:
public int hashCode()
5. equals(PairObject1, PairObject2):
It tests the pair for equality with the other pair. In case the object is not specified for testing or is null, then it will return false. The two pairs will be considered as one if and only if their names and values tend to be the same. We can declare it as:
public boolean equals(Object o)
It takes ‘-o’ arguments object to check the equality of the pair. It overrides the equal present in the class Objects and returns true of the pair is equal. In the other case, it returns false when the pair is not equal.
Example snippet to understand the equals() method:
Pair p1 = new Pair(10,5); Pair p2 = new Pair(10,5); Pair p3 = new Pair(6,7); System.out.println(p1.equals(p2)); //results in true System.out.println(p2.equals(p3)); //results in false
Here is a problem statement to understand these methods further:
Consider a scenario that there exists a list of n students along with their marks attained in an exam. Noa, we must find the student with the maximum score. Here is the program code to attain this desired result.
//Java program to find the Pair which has the maximum score
import javafx.util.Pair; import java.util.ArrayList; class FirstCodeScore { public static Pair <String,Integer> getMaximum(ArrayList < Pair <String,Integer> > l) { 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; } public static void main (String[] args) { int n = 5;//Number of Students ArrayList <Pair <String,Integer> > l = new ArrayList <Pair <String,Integer> > (); l.add(new Pair <String,Integer> ("Student A", 30)); l.add(new Pair <String,Integer> ("Student B", 44)); l.add(new Pair <String,Integer> ("Student C", 69)); l.add(new Pair <String,Integer> ("Student D", 98)); l.add(new Pair <String,Integer> ("Student E", 84)); Pair <String,Integer> ans = getMaximum(l); System.out.println(ans.getKey() + " has scored the first mark of" + ans.getValue()); } }
Output:
6. toString()
It denotes the pair as a String. In this method, the default name or the value delimiter ‘=’ is always used. Using it, we can override the toString in the class Object and return the String value of the pair. we can declare it as:
public String toString()
Syntax of Constructor of Java Pair class:
Pair<Integer, String> pair = new Pair<>(3, "Three"); Integer key = pair.getKey(); String value = pair.getValue();
Need for Pair Class in Java:
The pair values in Java return two values from a method. There are many reasons to use the Pair class.
Some of the major reasons are as follows:
- If we want to return multiple values, we imply data structures like Arrays and HashMap. In situations where we deal with multiple variables that have complications while being returned, the Pair class concept lends a helping hand.
- Performing mathematical operations and displaying the input with its output is simple using the Pair class.
- It is also useful to perform an operation on a tree data structure.
Let us understand with the help of an example.
Consider that a method returns both the cube root value of a number and the number itself. In such case, we need to merge a number with its cube root as a pair.
The results of this combination would be (number, cube root of the number), (125, 5), and (216, 6).
Types of Pair Class in Java:
The pair class in Java is classified into two categories:
- Mutable Pair
- Immutable Pair
1. Java Immutable Pair Class:
This class does not give the flexibility to change the value of the object after defining it. We cannot use the setters method to alter the given values. Here, the value remains constant.
Sample program to implement immutable pair class:
public class FirstCodePair<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(10,5); Pair <Integer> answer= new Pair <Integer>( ); answer = pair.getValue(); System.out.println(answer.p1 + " " + answer.p2); } }
Output:
2. Java Mutable Pair Class:
This class allows us to alter the given value anytime. The getters and setters method lets us access and alter the values of the object in the program. Though they are defined, they can be changed anytime. The methods that let us set and access the object value are pairs.setValue(a, b) and pair.getvalue() methods.
Sample program to implement Pair class:
FirstCode.java: import javafx.util.Pair; public class FirstCode public static void main(String[] args) { Pair<Integer, String> p = new Pair<>(2,"Two"); System.out.println("The key is :" + p.getKey()); System.out.println("The Pair value is :" + p.getValue()); } }
Output:
The key is: 2The Pair value is: Two
Java Customized Pair Class:
public class CustomizedPair { int key; String value; public CustomizedPair(int key, String value) { this.key = key; this.value = value; } public void print(){ System.out.println("< "+key+", "+value+ " >"); } public static void main(String[] args){ CustomizedPair a = new CustomizedPair(1,"FirstCode"); a.print(); } }
Here, we have created the Customized Pair class that stores two values in a single variable and prints it.
Output:
Pair class in action:
In order to use the pair class that we have just created, we must define an object of the pair class and class the constructor.
Pair a = new Pair(3, “Firstcode”);
Sample program to implement pair class in action:
public class FirstCodePair{ int first; String second; public Pair(int first, String second) { this.first = first; this.second = second; } public void print(){ System.out.println("< "+first+", "+second+ " >"); } public static void main(String[] args){ Pair a = new Pair(3,"FirstCode"); a.print(); } }
Output:
Java Pair class with Functions:
Pair class also helps us in returning values using functions. For this, we must mention the return type of the function.
Sample program to implement pair class with functions:
import java.util.Scanner; public class FirstCode{ public static void main(String[] args) { Scanner s = new Scanner(System.in); FirstCode f = func(s); f.print(); } public static FirstCode (Scanner s){ System.out.println("Enter a key: "); String key = s.next(); System.out.println("Enter a value: "); int value = s.nextInt(); FirstCode f= new FirstCode(value, key); return a; } }
Output:
Enter a key:Five
Enter a value:
5
< 5, Five >
Sample program to illustrate the use of Pair Class:
import javafx.util.Pair; import java.util.*; public class FirstCode { public static void main(String[] args) { Pair<String,String>p1=new Pair<>("Learn Java","tutorials and blogs"); Pair<String,String>p2=new Pair<>("Learn C++","easily"); Pair<String,String>p3=new Pair<>("Also Learn Python","via sample programs"); ArrayList<Pair<String,String>> listofpairs = new ArrayList<>(); listofpairs.add(p1); listofpairs.add(p2); listofpairs.add(p3); for(Pair<String,String> p:listofpairs) { System.out.println(p.getKey()+" with FirstCode "+p.getValue()); } } }
Output:
Learn Java with FirstCode tutorials and blogsLearn C++ with FirstCode easily
Also Learn Python with FirstCode via sample programs
Conclusion:
Now, you can use the pair class in Java to store the key-value pairs easily. Using the javafx.util.pair class, this task becomes simple. You can also try out implementing the different types of pair classes according to the needs and requirements.