Explore Pair Class in Java With Examples

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

Pair classes –  Well seems like if someone really wanted to have a class called pair, they would have created it themselves.

True, but there is more to it than what the eye sees.

Java didn’t have a pair class until Java 7.

JavaFX had a util package which now contains the pair class.

The pair class allows the programmer to store data in the form of pairs. Well, you could have done that way easily by declaring a class yourself.

The pair class comes with more than that out of the box. Let us dive in!

What is Pair Class in Java?

The pair class in Java is under the util package of the JavaFX package. However the value-value pairs have to be stored with the help of a parameterized constructor,

Let us see what it’s like to use it.

Pair Class Methods in Java

Methods of pair class in java

The Pair class has the following methods to support extensive usage.

  • Pair(Value1, Value2) – This constructor assigns two values to the Pair class. Simple. Direct.
  • equals(Pairobject1, PairObject2) – This returns a boolean value based on the value of the two pairs. Do note that the comparison checks the values of both the pairs. This is also popularly known as Deep comparison.
  • getKey() – As the name suggests, the method returns the key of the pair. This is generally the first value of the pair. It is of the same type as the datatype of the Key.
  • getValue() – As the name suggests, the method returns the value of the pair. This is generally the second value of the pair. It is of the same data type as that of the Value of the pair.
  • toString() – This method will return the String representation of the Pair.
  • hashcode() – This method is responsible for returning the hashcode of the pair.

Need of Pair Class in Java

We need a “pair class” for a lot of reasons.

One primary example would be when we want to return multiple values. I know some of you might be thinking about arrays and other data structures.

But if you are using a cluster of variables together then returning both of them together will be a hassle.

Then the pair class would be useful.

If you want to perform some mathematical calculations on a number and then return the number along with the result, you would generally be able to do it with a pair class very easily.

Syntax:

In Java, declaring Pair class objects are similar to normal object creation. Its syntax is as follows:

Pair<Wrapper Class1, Wrapper Class2>object_name = new Pair<>();

Types of Pair Class in Java

 

There are primarily two types of pair classes in Java:

1. Immutable Pair Class – This is a type of class where you cannot use setter methods to change the values of the pair according to your choice.

Generally, when we set the values of an immutable pair we cannot change it again.

2. Mutable Pair Class – This type of class allows you to change the values even after you set them at the beginning.

Simply speaking, this class allows you to use getter and setter methods such as pair.setValue(a,b) and pair.getValue() methods.

Defining a Custom Pair Class in Java

We can explicitly define our own pair class in Java. We will see how it goes.

Java program to illustrate the use of a user-defined Pair class:

package com.dataflair.pairclass;
class Pair
{
    int value1;
    int value2;
    Pair(int a, int b)
    {
        value1=a;
        value2=b;
        
    }
    
}
public class Main
{
    public static void main(String[] args) {
        //Here is an example of how you can set up your own pair class in java.
        Pair b = new Pair(3,4);
        //add methods to the class as you like.
        //You can also make it generic in nature!
        System.out.println("Example of custom pair class in Java.");
        System.out.println("The Pair is <"+b.value1+","+b.value2+">");
    }
}

Output:

Example of custom pair class in Java.
The Pair is <3,4>

We can create our own class based on our requirements anyway.

But Java already has a predefined class to suit our needs.

Java program to illustrate the use of the Pair class:

package com.dataflair.pairclass;

import javafx.util.Pair;
import java.util.*;

public class Main
{
    
    public static void main(String[] args) {
        Pair<String,String>p1=new Pair<>("WINDOWS","it's GUI");
        Pair<String,String>p2=new Pair<>("LINUX","it is open source and secure");
        Pair<String,String>p3=new Pair<>("MAC OS","its productivity");
        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()+" is famous for "+p.getValue());
        }
        
    }
}

Output:

WINDOWS is famous for it’s GUI
LINUX is famous for it is open source and secure
MAC OS is famous for its productivity

Functions with Pair Class

We can also use Pair class with functions in a program. Since these are objects we can also return pair objects from functions.

Let us see an example:

Java program to illustrate the use of Pair classes in a function:

package com.dataflair.pairclass;

import javafx.util.Pair;
import java.util.*;

public class Main
{
    public static Pair pairfunc(String firstname,String lastname)
    
    {
        Pair<String,String> name = new Pair<>(firstname,lastname);
        
        return name;
    
    }
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your first name");
        String fname=sc.nextLine();
        System.out.println("Enter your last name");
        String lname=sc.nextLine();
        Pair result=pairfunc(fname,lname);
        System.out.println("Hi there "+ result.getKey()+" "+result.getValue());
        
        
    }
}

Output:

Enter your first name
Shraman
Enter your last name
Das
Hi there Shraman Das

Summary

We learnt a lot about the usage of the pair class in Java and how it can be leveraged to suit our needs in programming.

It allows us to store two values together inside a single reference object. It also provides several other methods which come in handy.

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

Leave a Reply

Your email address will not be published. Required fields are marked *