Five Alternatives To Pair Class In Java

May 13, 2022
Five Alternatives to Pair Class in Java



Overview

In this post we will understand one of the key programming concepts known as Pairing. It is used when we want two values to be returned from a method. For example, a method that returns both the square root of the number and the number itself. Therefore, we need to merge a number with its square root in a pair. This pair or combination may result in (number, square root of a number). For example, (25, 5), (36, 6) and (49,7) etc.

Pairing is a concept which was already available in C++ language and developers who have worked in that language would certainly know about its’ working.

Pair Class in Java

By definition, Pair is a container or placeholder that provides a handy way to store a simple key to value. It stores a tuple of two objects. Pair class does not specify the relationship between the specified values but is often useful to track two objects together.

In Java there are two types of Pairs i.e. Mutable, for which we can change the data values and Immutable, for which we can’t change or set the data values.

Now let’s discuss the alternatives we have through which we can implement Pairs in Java.

1. Java 8 – javafx.util.Pair

In Java 8 and above, Pair<K,V> class is added in javafx.util package. The class represent key-value pairs and supports basic operations like getKey(), getValue(), hashCode(), equals(java.lang.Object o), and toString() and has few methods inherited from java.lang.Object class.

Let’s take a look with an example:

// Import required classes
import javafx.util.Pair;

import java.util.ArrayList;
import java.util.List;

class Main
    {
      // Demonstrates javafx.util.Pair class introduced in Java 8 and onwards
      public static void main(String[] args)
   {
       List<Pair<String, Integer>> name_age_Pair = new ArrayList<>();

      name_age_Pair.add(new Pair<>("Waqas", 40));
      name_age_Pair.add(new Pair<>("Talha", 37));

  // print first name-age pair using getKey() and getValue() method
 System.out.println("{" + name_age_Pair.get(0).getKey() + ", " +
  name_age_Pair.get(0).getValue() + "}");
 
   // print second name-age pair using getKey() and getValue() method
  System.out.println("{" + name_age_Pair.get(1).getKey() + ", " +
  name_age_Pair.get(1).getValue() + "}");
  }
  }

Output:
{Waqas, 40}
{Talha, 37}

2. Map.Entry<K,V> Interface

Map.Entry<K,V> interface in Java is similar to std::pair in C++. To create an entry representing a mapping from the specified key to the specified value, Java provides two concrete implementations of the Map.Entry interface, namely, AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry.

Here is the example:

import java.util.AbstractMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
class Pair

{

    // Return a map entry (key-value pair) from the specified values
    public static <T, U> Map.Entry<T, U> of(T first, U second) {
        return new AbstractMap.SimpleEntry<>(first, second);

    }

}

class Main
{
   // Demonstrates Pair class in Java using Map.Entry
    public static void main(String[] args)
    {

        Set<Map.Entry<String, Integer>> name_age_Pair= new HashSet<>();

        name_age_Pair.add(Pair.of("Waqas", 40));
        name_age_Pair.add(Pair.of("Talha", 37));

        System.out.println(name_age_Pair);
        // runs in Java 8 and above only
        name_age_Pair.forEach(entry -> {
            if (entry.getKey().equals("Waqas")) {
                System.out.println(entry.getValue());
            }
        });
    }
}

Output:

[Waqas=40, Talha=37]
40

3. JavaTuples Library

This is a Java library that deals with tuples. It provides a set of tuple Java classes ranging from one to ten elements. For our requirement, we can use Pair<A,B> class.

Let’s understand with the following code snippet:

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

class Main

{
    // Demonstrates Pair class provided by JavaTuples Library in Java

    public static void main(String[] args)

    {

        List<Pair<String, Integer>> name_age_Pair = new ArrayList<>();

        name_age_Pair.add(Pair.with("Waqas", 40));    // using Pair.with()
        name_age_Pair.add(new Pair<>("Talha", 37));   // using constructors

        // print first name-age pair using getValue0() and getValue1() method

        System.out.println("{" + name_age_Pair.get(0).getValue0() + ", " +

                            name_age_Pair.get(0).getValue1() + "}");

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

    }

}

Output:

{Waqas, 40}
{Talha, 37}

4. Apache Commons Lang

Apache Commons Lang library provides a Pair<L,R> utility class, elements of which are left and right. It is defined as an abstract and implements the Map.Entry interface, where the key is left and the value is right.

It also has Pair.of() method that can be used to obtain an immutable pair from specified pair of objects. Its subclass MutablePair is mutable, whereas ImmutablePair is immutable. However, the type of the object stored in ImmutablePair can itself may be mutable.

Let’s see with an example:

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

import java.util.ArrayList;
import java.util.List;

  class Main
  {
  // Demonstrates Pair class provided by Apache Commons Library in Java
  public static void main(String[] args)
  {
List<Pair<String, Integer>> name_age_Pair = new ArrayList<>();

  name_age_Pair.add(new MutablePair<>("Waqas", 40)); // using MutablePair
  name_age_Pair.add(new ImmutablePair<>("Talha", 37)); // using ImmutablePair
  name_age_Pair.add(Pair.of("Arham", 14)); // using Pair.of()

System.out.println(name_age_Pair);

 // The first name-age pair is mutable
Pair<String, Integer> pair = name_age_Pair.get(0);
pair.setValue(100); // works fine

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

// The second name-age pair is immutable
pair = name_age_Pair.get(1);
try {
pair.setValue(100); // runtime error
}
catch (UnsupportedOperationException ex) {
System.out.println("Unsupported Operation Exception thrown");
}

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

 // The third name-age pair is also immutable
  pair = name_age_Pair.get(2);
  try {
  pair.setValue(100); // runtime error
}
    catch (UnsupportedOperationException ex) {
   System.out.println("Unsupported Operation Exception thrown");
 }
     System.out.println(pair.getLeft() + ", " + pair.getRight());
  }
}

Output:
[(Waqas,40), (Talha,37), (Arham,14)]
Waqas, 100
Unsupported Operation Exception thrown
Talha, 37
Unsupported Operation Exception thrown
Arham, 14

5. Collections.singletonMap() method

And finally the last technique is to use the Collections.singletonMap() which is similar to Map.Entry<K,V> discussed above. It returns an immutable singleton map containing only the specified key-value pair mapping, which can be treated as a Pair.

Here is an example:

import java.util.Collections;

import java.util.HashSet;

import java.util.Map;

import java.util.Set;

class Pair

{

   // Return an immutable singleton map containing only the specified key-value pair mapping

    public static <T, U> Map<T, U> of(T first, U second) {

        return Collections.singletonMap(first, second);

    }

}

class Tuple

{

    // Demonstrates Pair class in Java using Collections.singletonMap()

    public static void main(String[] args)

    {

       Set<Map<String, Integer>> name_age_Pair = new HashSet<>();

     name_age_Pair.add(Pair.of("Waqas", 40));

        name_age_Pair.add(Pair.of("Arham", 14));

        System.out.println(name_age_Pair);

    }

}

Output:

[{Waqas=40}, {Arham=14}]

Conclusion

In this post we have seen five alternatives to pair classes in Java. These techniques are quite useful and handy for developers who would like to use them in their programs and can cherry pick any of the alternative they deem fit.

Also Read: Guide to the Synchronized Keyword in Java

 



author

shaharyar-lalani

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US