• Register
294 points
ā—3

Pair Class in Java

It is class of javafx.util packag.
 
Methods provided by JAVA 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 = new Pair(3,4);
Pair p2 = new Pair(3,4);
Pair p3 = new Pair(4,4);
System.out.println(p1.equals(p2) + ā€œ\nā€ + p2.equals(p3));

 Output :-

true 
false
  • 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
import javafx.util.Pair;
import java.util.ArrayList;
  
class Demo
{
    public static Pair <String,Integer>
              getMaximum(ArrayList < Pair <String,Integer> > l)
    {
        // Assign minimum value initially
        int max = Integer.MIN_VALUE;
  
        Pair <String, Integer> ans = 
                         new Pair <String, Integer> ("", 0);

        for (Pair <String,Integer> temp : l)
        {
            // Get the score of Student
            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
  
        //Create an Array List
        ArrayList <Pair <String,Integer> > l =
                  new ArrayList <Pair <String,Integer> > ();

        l.add(new Pair <String,Integer> ("Student A", 90));
        l.add(new Pair <String,Integer> ("Student B", 54));
        l.add(new Pair <String,Integer> ("Student C", 99));
        l.add(new Pair <String,Integer> ("Student D", 88));
        l.add(new Pair <String,Integer> ("Student E", 89));
  
        // get the Pair which has maximum value
        Pair <String,Integer> ans = getMaximum(l);
  
        System.out.println(ans.getKey() + " is top scorer " +
                          "with score of " + ans.getValue());
    }
}

Output :-

Student C is top scorer with score of 99

 

2 Comments

Really helpful article. I have been learning Java for quite some time now but always struggled with pair class. This really helped me understand the pair class.
I was in despair before reading this. How can I not understand this simple topic? You made it really simple. Thanks a lot.