Five Java Pair Class Replacements You Should Know
In this post, let’s explore a fundamental programming concept known as Pairing. It comes into play when we require two values to be returned from a method, such as when a method needs to provide both the square root of a number and the number itself. Consequently, there’s a need to unite a number with its corresponding square root in a pair. This pairing or combination results in (number, square root of the number), as seen in examples like (25, 5), (36, 6), and (49, 7), among others.
Pairing is a concept that has been a part of the C++ language for some time, and developers familiar with that language will likely be acquainted with its functionality.
Understanding Pairing in Java
In the vast landscape of Java programming, the Pair class stands as a testament to versatility, providing a practical vessel for housing key-value pairs. This class excels at encapsulating a duo of objects within a single entity, granting developers the capacity to consolidate related data without having to explicitly define their precise interconnection.
Java caters to the needs of developers with two distinct flavors of Pair implementations: Mutable and Immutable;
- The Mutable Pairs offer the advantage of adaptability, allowing you to fine-tune the data they hold to suit your evolving requirements.
- Immutable Pairs prioritize data security and integrity, rigidly guarding against any alterations to their core values.
Now, let us embark on a journey through a rich landscape of alternative approaches, exploring various avenues for achieving Pair-like functionality within the Java programming realm. Each alternative bears its unique set of characteristics, ready to empower developers in crafting tailored solutions to meet a multitude of coding challenges.
Method/Library | Description | Example |
javafx.util.Pair | Introduced in Java 8 and onwards, it handles key-value pairs and inherits methods from java.lang.Object. | Pair<String, Integer> pair = new Pair<>(“Waqas”, 40); |
Map.Entry<K, V> Interface | Provides a standard interface for key-value pairs in Java. Java offers implementations like AbstractMap.SimpleEntry. | Map.Entry<String, Integer> entry = Pair.of(“Waqas”, 40); |
JavaTuples Library | Offers a variety of tuple Java classes, including Pair<A, B>, for managing tuples with different element counts. | Pair<String, Integer> pair = Pair.with(“Waqas”, 40); |
Apache Commons Lang | Provides a utility class named Pair<L, R> with Mutable and Immutable variations for key-value pairs. | Pair<String, Integer> pair = new MutablePair<>(“Waqas”, 40); |
Collections.singletonMap() | Returns an immutable singleton map containing a specified key-value pair, which can be treated as a Pair. | Map<String, Integer> singletonMap = Collections.singletonMap(“Waqas”, 40); |
Java 8 – javafx.util.Pair
Java 8 and later versions introduce the Pair<K, V> class, which resides within the javafx.util package. This class is designed to facilitate the handling of key-value pairs and offers essential functionalities such as getKey(), getValue(), hashCode(), equals(java.lang.Object o), and toString(). Additionally, it inherits several methods from the java.lang.Object class.
Let’s illustrate this 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}
Map.Entry<K,V> Interface
The Map.Entry<K, V> interface in Java shares similarities with the std::pair in C++. Java offers two concrete implementations of the Map.Entry interface, AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry, to create entries that represent mappings from a specified key to a specified value.
Here’s an illustrative 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
JavaTuples Library
This Java library specializes in managing tuples, offering a collection of tuple Java classes with varying element counts, spanning from one to ten elements. For our specific needs, the Pair<A, B> class can serve as an ideal choice.
Let’s gain insight through the following code excerpt:
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}
Apache Commons Lang
The Apache Commons Lang library offers a utility class named Pair<L, R>, where the elements are referred to as left and right. This class is defined as abstract and implements the Map.Entry interface, with the key as the left element and the value as the right element.
Furthermore, it includes a convenient Pair.of() method for obtaining an immutable pair from a specified pair of objects. While the MutablePair subclass allows for mutability, ImmutablePair ensures immutability. However, it’s worth noting that the type of object stored in ImmutablePair may itself be mutable.
Let’s illustrate this 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
Collections.singletonMap() method
Alt: Collections.singletonMap() method in javascript coding
Lastly, another technique involves utilizing the Collections.singletonMap(), which shares similarities with the earlier discussed Map.Entry<K, V>. It yields an immutable singleton map, encompassing only the designated key-value pair mapping, effectively serving as a Pair.
Let’s exemplify this with 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
Throughout this article, this exploration delves into a diverse array of five alternatives to pair classes in Java. These versatile techniques offer a wealth of options for developers seeking to enhance their programming endeavors. Whether you’re seeking greater flexibility, improved performance, or enhanced functionality, you have the freedom to select the alternative that best aligns with your specific needs and objectives. These alternatives open up new horizons in Java development, empowering developers to craft more efficient and elegant solutions for a wide range of programming challenges.
No Comments
Sorry, the comment form is closed at this time.