What is a Pair Class in Java?

Filed Under: Java
Pair Class in Java

Java Pair class stores two values in the form of a tuple. This can be useful to get a function to return two values.

Java has an inbuilt Pair class from Java 8 onwards. That is why in this lesson we will not only look at the inbuilt pair class but also learn how to make our own pair class.

Pair class is very useful when using a Tree data structure. While using recursion on a tree, pair class makes it easy to pass values from one node to another. These values can be minimum and maximum node value up to that node. This would prevent revisiting certain nodes again and again.

In-built Pair class in Java

Inbuilt Pair class is a part of the JavaFX package. However, this package is not part of the standard OpenJDK installation. We can add it to our project using the following maven dependencies.

<dependency>
	<groupId>org.openjfx</groupId>
	<artifactId>javafx-base</artifactId>
	<version>14.0.1</version>
</dependency>

Let’s get right to the usage of the inbuilt pair classes in Java.

Importing Pair class

To import use:

import javafx.util.Pair;

Inbuilt pair class uses the notation of Key and Value to store a pair.

<Key, Value>

However, don’t confuse it with HashMap.

Declaring a Pair object

 Pair<Integer, String> p = new Pair<>(7,"Hello");

This creates a pair object of the type <Integer, String> .

The constructor takes the values 7 and “hello” and stores them in the Pair class.

Accessing values

We can access values from Pair object using getKey() and getValue() methods.

  • getKey gets the first value.
  • getValue gets the second value.
System.out.println("the first value is :" + p.getKey());
System.out.println("the first second is :" + p.getValue());
Pairclass Output
Output

The complete code for this section is :

import javafx.util.Pair;

public class Main {

public static void main(String[] args)
{
Pair<Integer, String> p = new Pair<>(7,"Hello");
System.out.println("the first value is :" + p.getKey());
System.out.println("the first second is :" + p.getValue());
}
}

Creating our own Pair class

Creating our own pair class is a better alternative as we can customize it according to our own preference. Also, if you are not using JavaFX in your project, it makes sense to avoid it completely.

1. Defining the Custom Pair class

For the purpose of simplicity, we are using a pair class that stores two values. An Integer and a String. Using generics would be a good idea too.

public class Pair {
        int first;
        String second;
        public Pair(int first, String second) {
            this.first = first;
            this.second = second;
        }
}

Two variables first and second have been defined to store two values of the type int and String respectively.

The constructor takes two values and assigns them to the variables.

2. Pair class in action

To use the pair class just created, define an object of the pair class and call the constructor.

Pair a = new Pair(1, "one");

This creates a pair object with 1 stored in first and “one” stored in second.

To access the values :

System.out.println("the first value is :" + a.first);
System.out.println("the first second is :" + a.second);
Self Created Pair Output
Output

Since pair class is defined by us, we can customize and add a print function to it.

Code for pair class :

 public class Pair {
        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(1,"Hello");
            a.print();
        }
}
print -pairclass
output

Including a print function, this way is a good coding habit as now the variables could be made private. Keeping the variables public is not safe.

Using Pair class with a function

Pair class can be used to return two values from a function. To do this, the return type of the function must be pair.

 public static Pair func (Scanner s){
    System.out.println("what is your name");
    String name = s.next();
    System.out.println("what is your favourite number?");
    int num = s.nextInt();
    Pair ans = new Pair(num, name);
    return ans;
}

The object that is returned from this function can be captured in the main function. Let’s print the object in the main.

public static void main(String[] args) {
Scanner s = New Scanner(System.in)
Pair ans = func(s);
ans.print();
}
Pair With Function
Output

The complete code for this section is as follows.

import java.util.Scanner;

public class Main {       
public static void main(String[] args) {
Scanner s = New Scanner(System.in)
Pair ans = func(s);
ans.print();
}

public static Pair func (Scanner s){
System.out.println("what is your name");
String name = s.next();
System.out.println("what is your favourite number?");
int num = s.nextInt();
Pair ans = new Pair(num, name);
return ans;
}
}

Conclusion

Pair classes are important and can improve the efficiency of the code if used properly. One interesting area to use pair class is to store the maximum and minimum values of a subtree in BST problems. This saves the multiple traversals down the tree.

Comments

  1. Vishal Nandu Kangane says:

    Don’t you think that custom pair class is similar to normal class in java. And we can return object in java which can hold any type of data then why we need this??

    1. Pankaj says:

      Yes, you are correct. If you are using JavaFX, then use the built-in Pair class, else write it yourself if needed. It’s a very simple class, nothing fancy things.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages