In C++, we have std::pair in the utility library which is of immense use if we want to keep a pair of values together. We were looking for an equivalent class for pair in Java but Pair class did not come into existence till Java 7. JavaFX 2.2 has the javafx.util.Pair class which can be used to store a pair. We need to store the values into Pair using the parameterized constructor provided by the javafx.util.Pair class.
Note: Note that the <Key, Value> pair is used in HashMap/TreeMap. Here, <Key, Value> simply refers to a pair of values that are stored together.
Methods provided by the javafx.util.Pair class
Syntax: The pair class in the Java method
Pair<Key Type, Value Type> var_name = new Pair<>(key, value);
- Pair (K key, V value): Creates a new pair.
- boolean equals(): It is used to compare two pairs of objects. It does a deep comparison, i.e., it compares on the basis of the values (<Key, Value>) which are stored in the pair objects.
Example:
java
Pair p1 = new Pair(3, 4);
Pair p2 = new Pair(3, 4);
Pair p3 = new Pair(4, 4);
System.out.println(p1.equals(p2) + “ ” + p2.equals(p3));
Output:
true false
- String toString(): This method will return the String representation of the Pair.
- K getKey(): It returns the key for the pair.
- V getValue(): It returns a value for the pair.
- int hashCode(): Generate a hash code for the Pair.
Accessing values: Using getKey() and getValue() methods we can access a Pair object’s values.
1. getKey(): gets the first value.
2. getValue(): gets the second value
Note: Here, <Key, Value> refers to a pair of values that are stored together. It is not like <Key, Value> pair which is used in Map.
Implementation:
Java
// Java program to implement in-built pair classes
import javafx.util.Pair;
class GFG {
// Main driver method
public static void main(String[] args)
{
Pair<Integer, String> p
= new Pair<Integer, String>(10, "Hello Geeks!");
// printing the values of key and value pair
// separately
System.out.println("The First value is :"
+ p.getKey());
System.out.println("The Second value is :"
+ p.getValue());
}
}
Note: The javafx.util.Pair class is part of the JavaFX library. Starting with Java 11, JavaFX has been decoupled from the JDK. Even in Java 8, it might not be included in all JDK distributions. To use this class, you may need to manually add JavaFX dependencies via OpenJFX or other sources.
Alternative Implementation:
If javafx.util.Pair is unavailable or if you prefer not to use JavaFX, consider these alternatives listed below:
1. Using AbstractMap.SimpleEntry:
Java
AbstractMap.SimpleEntry<String, Integer> pair = new AbstractMap.SimpleEntry<>("Student A", 85);
System.out.println("Key: " + pair.getKey());
System.out.println("Value: " + pair.getValue());
2. Using a Custom Pair Class:
Java
class Pair<K, V> {
private final K key;
private final V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
Let us have a look at the following problem.
Problem Statement: We are given the names of n students with their corresponding scores obtained in a quiz. We need to find the student with the maximum score in the class.
Note: You need to have Java 8 installed on your machine in order to run the below program.
Java
// Java program to find a Pair which has maximum score
// Importing required classes
import java.util.ArrayList;
import javafx.util.Pair;
// class
class Test {
// This method returns a Pair which hasmaximum score
public static Pair<String, Integer>
getMaximum(ArrayList<Pair<String, Integer> > l)
{
// Assign minimum value initially
int max = Integer.MIN_VALUE;
// Pair to store the maximum marks of a
// student with its name
Pair<String, Integer> ans
= new Pair<String, Integer>("", 0);
// Using for each loop to iterate array of
// Pair Objects
for (Pair<String, Integer> temp : l) {
// Get the score of Student
int val = temp.getValue();
// Check if it is greater than the previous
// maximum marks
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 Students
// Create an Array List
ArrayList<Pair<String, Integer> > l
= new ArrayList<Pair<String, Integer> >();
/* Create pair of name of student with their
corresponding score and insert into the
Arraylist */
l.add(new Pair<String, Integer>("Student A", 90));
l.add(new Pair<String, Integer>("Student B", 54));
l.add(new Pair<String, Integer>("Student C", 99));
l.add(new Pair<String, Integer>("Student D", 88));
l.add(new Pair<String, Integer>("Student E", 89));
// get the Pair which has maximum value
Pair<String, Integer> ans = getMaximum(l);
System.out.println(ans.getKey() + " is top scorer "
+ "with score of "
+ ans.getValue());
}
}
Output:
Student C is top scorer with score of 99
Note: The above program might not run in an online IDE, please use an offline compiler.
Alternative Implementation:
Example: Here, the below Java program demonstrates how to use streams to find the entry with the maximum value in a list of AbstractMap.SimpleEntry objects.
Java
// Java program to demonstrate the use of stream
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.List;
public class Geeks {
public static void main(String[] args)
{
List<AbstractMap.SimpleEntry<String, Integer> > s
= Arrays.asList(new AbstractMap.SimpleEntry<>(
"Student A", 85),
new AbstractMap.SimpleEntry<>(
"Student B", 92),
new AbstractMap.SimpleEntry<>(
"Student C", 99));
AbstractMap.SimpleEntry<String, Integer> t
= s.stream()
.max(
(p1, p2)
-> Integer.compare(p1.getValue(),
p2.getValue()))
.orElseThrow();
System.out.println(
t.getKey()
+ " is the top scorer with a score of "
+ t.getValue());
}
}
OutputStudent C is the top scorer with a score of 99
Note:
- The javafx.util.Pair class can be convenient if you are already using JavaFX in your project.
- For standalone or non-GUI applications, alternative implementations might be more suitable.
Similar Reads
Pair Class in JavaTuples
A Pair is a Tuple from JavaTuples library that deals with 2 elements. Since this Pair is a generic class, it can hold any type of value in it.Since Pair is a Tuple, hence it also has all the characteristics of JavaTuples: They are TypesafeThey are ImmutableThey are IterableThey are SerializableThey
5 min read
JavaFX | Insets Class
Insets class is a part of JavaFX. Insets class stores the inside offsets for the four sides of the rectangular area. Insets class inherits java.lang.Object class. Constructors of the class: Insets(double a): Constructs a new Insets instance with same value for all four offsets. Insets(double top, do
4 min read
JavaFX | Point2D Class
Point2D class is a part of JavaFX. This class defines a 2-dimensional point in space. The Point2D class represents a 2D point by its x, y coordinates. It inherits java.lang.Object class.Constructor of the class: Point2D(double x, double y): Create a point2D object with specified x and y coordinates.
4 min read
Joiner class | Guava | Java
Guava's Joiner class provides various methods to handle joining operations on string, objects, etc. This class provides advanced functionality for the join operation. Declaration: Following is the declaration for com.google.common.base.Joiner class : @GwtCompatible public class Joiner extends Object
2 min read
Java StringJoiner Class
StringJoiner class in Java provides an efficient way to concatenate multiple strings with a defined delimiter(character), optional prefix, and suffix. This class is especially useful when constructing formatted strings dynamically. Example 1: [GFGTABS] Java // Demonstration of StringJoiner Class imp
3 min read
Join two ArrayLists in Java
Given two ArrayLists in Java, the task is to join these ArrayLists. Examples: Input: ArrayList1: [Geeks, For, ForGeeks] , ArrayList2: [GeeksForGeeks, A computer portal] Output: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal] Input: ArrayList1: [G, e, e, k, s] , ArrayList2: [F, o, r, G, e, e
1 min read
DuoDecimal in Java
Duodecimal represents a system which is a notation system in which a number having its base as 12 is called a duodecimal number. In java, we can use to find the conversation of duodecimal numbers into respective binary, octal, decimal, hexadecimal number, or any other base numbers. In java, we can u
4 min read
Set in Java
The Set Interface is present in java.util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored. It is an interface that implements the mathematical set. This interface adds a feature that restricts the insertion of duplicat
14 min read
Traverse through a HashSet in Java
As we all know HashSet elements are unordered so the traversed elements can be printed in any order. In order to perform operations over our HashSet such as insertion, deletion, updating elements than first we need to reach out in order to access the HashSet. below are few ways with which we can ite
3 min read
Compare two Strings in Java
String in Java are immutable sequences of characters. Comparing strings is the most common task in different scenarios such as input validation or searching algorithms. In this article, we will learn multiple ways to compare two strings in Java with simple examples. Example: To compare two strings i
4 min read