Core Java

Java Pair Class Example

1. Introduction to Java Pair Class

A Java pair class is a container a tuple of two objects. Pairs provide a convenient way of handling simple keys to value association and are particularly useful when we want to return two values from a method. A simple implementation of a Pair is available in the core Java libraries e.g. javafx.util.Pair.

In Java, maps are used to store key-value pairs. Maps store a collection of pairs and operate them as a whole.

Sometimes, we need to work on requirements where a key-value pair shall exist on its own. e.g.

  • A pair need to be passed in a method as an argument
  • The method need to return two values in the form of a pair

The syntax of the Pair class is as follows:

public class Pair extends Object implements Serializable

The syntax of the constructor of the Pair class:

public Pair(K key,V value)

2. Methods of Pair class

The following table displays the various methods of the Pair class with their description:

SyntaxDescriptionOverridesParametersReturns
public K getKey()Gets the key for this pair.key for this pair
public V getValue()Gets the value for this pair.value for this pair
public String toString()String representation of this Pair.
The default name/value delimiter ‘=’ is always used.
toString in class ObjectString representation of this Pair
public int hashCode()Generate a hash code for this Pair.
The hash code is calculated using both the name and the value of the Pair.
hashCode in class Objecthash code for this Pair
public boolean equals(Object o)Test this Pair for equality with another Object.
If the Object to be tested is not a Pair or is null, then this method returns false.
Two Pairs are considered equal if and only if both the names and values are equal.
equals in class Objecto – the Object to test for equality with this Pairtrue if the given Object is equal to this Pair else false

3. Java Pair class Example

The following examples show the usage of the Pair class.

PairDemo.java

import javafx.util.Pair; 
import java.util.ArrayList; 
  
public class PairDemo 
{ 
    /* This method returns a Pair which has maximum score*/
    public static Pair 
              getMaximum(ArrayList<Pair > l) 
    { 
        // Assign minimum value initially 
        int max = Integer.MIN_VALUE; 
  
        // Pair to store the maximum salary of an  
        // employee with his name 
        Pair ans = new Pair ("", 0); 
  
        // Using for each loop to iterate array of  
        // Pair Objects 
        for(Pair temp : l) 
        { 
            // Get the salary of Employee 
            int val = temp.getValue(); 
  
            // Check if it is greater than the previous  
            // maximum salary 
            if (val > max) 
            { 
                max = val;  // update maximum 
                ans = temp; // update the Pair 
            } 
        } 
        return ans; 
    } 
  
    // Driver method to test above method 
    public static void main (String[] args) 
    { 
         int n = 5;//Number of Employees 
  
        //Create an Array List 
        ArrayList<Pair> l = 
                  new ArrayList<Pair>(); 
  
        /*  Create pair of names of Employees  with their 
            corresponding salaries and insert into the Arraylist */
        
        l.add(new Pair("Employee A", 80000)); 
        l.add(new Pair("Employee B", 54000)); 
        l.add(new Pair("Employee C", 66000)); 
        l.add(new Pair("Employee D", 73000)); 
        l.add(new Pair("Employee E", 56000)); 
  
        // get the Pair which has maximum value 
        Pair ans = getMaximum(l); 
  
        System.out.println(ans.getKey() + " is highest earner " + 
                          "with salary of " + ans.getValue()); 
    } 
} 

Output

Employee A is highest earner with salary of 80000

4. Alternatives to Javafx Pair class

4.1 Apache commons Lang Library

Apache Commons Lang Library also provides a Pair<L, R> utility class whose elements are left and right. It is an abstract class and implements the Map interface. It has Pair.of() method that can be used to obtain an immutable pair of objects. Its subclass MutablePair is mutable and ImmutablePair is immutable, however, the type of objects stored in ImmutablePair can itself be mutable.

4.1.1 Apache commons Lang Library Pair<L,R> example

The following examples show the usage of the Pair<L, R> class under Apache commons Lang Library.

ApacheCommonsDemo.java

import javafx.util.Pair; 
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;

class Tuple
{
	// Demonstrate Pair class provided Apache Commons Library in Java
	public static void main(String[] args)
	{
		List<Pair> tuples = new ArrayList();

		tuples.add(new MutablePair("C", 20));		// using MutablePair
		tuples.add(new ImmutablePair("C++", 30));	// using ImmutablePair
		tuples.add(Pair.of("Java", 50));   			// using Pair.of()

		System.out.println(tuples);

		// Mutable pair
		Pair pair = tuples.get(0);
		pair.setValue(100); 

		// printing pair using getKey() and getValue() method
		System.out.println(pair.getKey() + ", " + pair.getValue());

		// Immutable pair
		pair = tuples.get(1);
		try {
			pair.setValue(100); // runtime error
		}
		catch (UnsupportedOperationException ex) {
			System.out.println("UnsupportedException thrown");
		}

		// printing pair using getLeft() and getRight() method
		System.out.println(pair.getLeft() + ", " + pair.getRight());

		// 3. third pair is also immutable
		pair = tuples.get(2);
		try {
			  pair.setValue(100);  //runtime error
		    }
		catch (UnsupportedOperationException ex) {
			System.out.println("UnsupportedException thrown");
		}
		System.out.println(pair.getLeft() + ", " + pair.getRight());
	}
}
  

Output

[(C,20), (C++,30), (Java,50)]
C, 100
UnsupportedException thrown
C++, 30
UnsupportedException thrown
Java, 50

4.2 JavaTuples Library

JavaTuples is another simple and famous Java library that deals with tuples. It provides a set of tuple Java classes ranging from 1 to 10 elements. To serve our purpose you can use Pair<A, B>, class.

4.2.1 JavaTuples Library example

The following examples show the usage of the Pair<A, B> class under JavaTuples Library.

JavaTuplesDemo.java

import org.javatuples.Pair;
import java.util.ArrayList;
import java.util.List;

class JavaTuples
{
	// Demonstrate Pair class provided JavaTuples Library in Java
	public static void main(String[] args)
	{
		List<Pair> tuples = new ArrayList();

		tuples.add(Pair.with("C", 50));	 // using Pair.with()
		tuples.add(new Pair("Java",100));	 // using constructors

		// print first pair using getValue0() and getValue1() method
		System.out.println("{" + tuples.get(0).getValue0() + ", " +
							tuples.get(0).getValue1() + "}");

		// print second pair using getValue0() and getValue1() method
		System.out.println("{" + tuples.get(1).getValue0() + ", " +
							tuples.get(1).getValue1() + "}");
	}
}

Output

{C, 50}
{Java, 100}

5. Conclusion

In this tutorial, we learned about the JavaFX.util.pair class and how it can be used to store paired tuples. Moreover, we saw the alternatives that can be used in place of JavaFX.util.Pair class to achieve a similar objective. Apart from the apache commons library and JavaTuples library we also have few other alternatives to JavaFX.util.pair class such as vavr library, Map.Entry Interface etc.

6. References

7. Download the source code

The following code shows the usage of JavaFX.util.pair, org.apache.commons.lang3.tuple.Pair and org.javatuples.Pair examples.

Download
You can download the full source code of this example here: Java Pair Class Example

Gaurav Verma

I am Gaurav Verma from Kolkata, India. I have done Bachelors of Technology in Computer Science & Engineering from Narula Institute of Technology under West Bengal University of Technology. I joined NIIT LTD. as a Technical Trainer in 2007 and trained students pursuing GNIIT and Bsc.IT curriculum as well as modular courses in various technologies like Java, .Net and Open Source technologies. I have been a very enthusiastic Java programmer and take lot of interest in programming through Java language and also develop Standalone and web applications using Java technologies. My favourite pass time are Solving Puzzles, Sudoku, watching documentaries etc.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button