Utilizing Pairs in Java Programming

JavaJavaBeginner
Practice Now

Introduction

Pairs are a way of storing paired data, consisting of two fields - one for the key and another for the value. In Java, Pairs are a great way of returning multiple values from a method. There are plenty of ways of using Pairs in Java. This lab will provide step-by-step guidance on how to use pairs in Java with code examples.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_attributes("`Class Attributes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/constructors("`Constructors`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/encapsulation("`Encapsulation`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("`Wrapper Classes`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/SystemandDataProcessingGroup -.-> java/object_methods("`Object Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/classes_objects -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/class_attributes -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/class_methods -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/constructors -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/encapsulation -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/modifiers -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/oop -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/packages_api -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/wrapper_classes -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/identifier -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/arrays -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/comments -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/data_types -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/operators -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/output -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/strings -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/object_methods -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} java/system_methods -.-> lab-117976{{"`Utilizing Pairs in Java Programming`"}} end

Create Java Class

Create a new Java class using the following command:

cd ~/project && touch PairsInJava.java

Implement Pair Class of JavaFX.Util Package

JavaFX provides a built-in Pair class, which can be used to work with pairs. In this step, we will learn how to use the Pair class to create and manipulate pairs. Add the following code to your PairsInJava.java file:

import javafx.util.Pair;

public class PairsInJava {
    public static void main(String[] args) {
        Pair<String, Integer> p1 = new Pair<>("apple", 1);
        Pair<String, Integer> p2 = new Pair<>("banana", 2);
        System.out.println("p1=" + p1.toString());
        System.out.println("p2=" + p2.toString());
        System.out.println("key of p1=" + p1.getKey());
        System.out.println("value of p1=" + p1.getValue());
    }
}

In the code above, we use the Pair class to create two pairs and then print their key and value for each pair.

To compile and run the code, execute the following command:

javac PairsInJava.java && java PairsInJava

Implement Object Arrays To Create Pairs In Java

In this step, we will learn how to implement object arrays to create pairs in Java. Add the following code to your PairsInJava.java file:

public class PairsInJava {
    public static void main(String[] args) {
        Object[] p1 = {"apple", 1};
        Object[] p2 = {"banana", 2};
        System.out.println("p1=" + p1[0] + "," + p1[1]);
        System.out.println("p2=" + p2[0] + "," + p2[1]);
    }
}

In the code above, we use an object array to create two pairs and then print their key and value for each pair.

To compile and run the code, execute the following command:

javac PairsInJava.java && java PairsInJava

Implement User-Defined Pair Class

In this step, we will learn how to implement a user-defined pair class to create pairs in Java. Add the following code to your PairsInJava.java file:

class MyPair<T1, T2> {
    private T1 key;
    private T2 value;

    public MyPair(T1 key, T2 value) {
        this.key = key;
        this.value = value;
    }

    public T1 getKey() {
        return key;
    }

    public T2 getValue() {
        return value;
    }

    public void setKey(T1 key) {
        this.key = key;
    }

    public void setValue(T2 value) {
        this.value = value;
    }
}

public class PairsInJava {
    public static void main(String[] args) {
        MyPair<String, Integer> p1 = new MyPair<>("apple", 1);
        MyPair<String, Integer> p2 = new MyPair<>("banana", 2);
        System.out.println("p1=" + p1.getKey() + "," + p1.getValue());
        System.out.println("p2=" + p2.getKey() + "," + p2.getValue());
    }
}

In the code above, we define a custom class MyPair to create pairs and then print their key and value for each pair.

To compile and run the code, execute the following command:

javac PairsInJava.java && java PairsInJava

Implement AbstractMap.SimpleEntry Class

In this step, we will learn how to create a pair using the AbstractMap.SimpleEntry class. Add the following code to your PairsInJava.java file:

import java.util.AbstractMap;

public class PairsInJava {
    public static void main(String[] args) {
        AbstractMap.SimpleEntry<String, Integer> p1 = new AbstractMap.SimpleEntry<>("apple", 1);
        System.out.println("p1=" + p1.getKey() + "," + p1.getValue());
        p1.setValue(2);
        System.out.println("new p1=" + p1.getKey() + "," + p1.getValue());
    }
}

In the code above, we use the AbstractMap.SimpleEntry class to create a pair and then modify its value.

To compile and run the code, execute the following command:

javac PairsInJava.java && java PairsInJava

Implement AbstractMap.SimpleImmutableEntry Class

In this step, we will learn how to create an immutable pair using AbstractMap.SimpleImmutableEntry class. Add the following code to your PairsInJava.java file:

import java.util.AbstractMap;

public class PairsInJava {
    public static void main(String[] args) {
        AbstractMap.SimpleImmutableEntry<String, Integer> p1 = new AbstractMap.SimpleImmutableEntry<>("apple", 1);
        System.out.println("p1=" + p1.getKey() + "," + p1.getValue());
        // cannot set the value
        // p1.setValue(2);
    }
}

In the code above, we use the AbstractMap.SimpleImmutableEntry class to create an immutable pair. We cannot modify its key and value once they have been initialized.

To compile and run the code, execute the following command:

javac PairsInJava.java && java PairsInJava

Implement javatuples Pair Class

In this step, we will learn how to use the Pair class from the javatuples library to create pairs. Add the following code to your PairsInJava.java file:

import org.javatuples.Pair;

public class PairsInJava {
    public static void main(String[] args) {
        Pair<String, Integer> p1 = Pair.with("apple", 1);
        Pair<String, Integer> p2 = Pair.with("banana", 2);
        System.out.println("p1=" + p1.getValue0() + "," + p1.getValue1());
        System.out.println("p2=" + p2.getValue0() + "," + p2.getValue1());
    }
}

In the code above, we use the Pair class from javatuples library to create and print key and value for each pair.

To compile and run the code, execute the following command:

javac -cp .:javatuples-1.2.jar PairsInJava.java && java -cp .:javatuples-1.2.jar PairsInJava

Implement Vavr Library's Tuple2 Class

In this step, we will learn how to use the Tuple2 class from the Vavr library to create pairs. Add the following code to your PairsInJava.java file:

import io.vavr.Tuple2;

public class PairsInJava {
    public static void main(String[] args) {
        Tuple2<String, Integer> p1 = new Tuple2<>("apple", 1);
        System.out.println("p1=" + p1._1() + "," + p1._2());
    }
}

In the code above, we use the Tuple2 class from the Vavr library to create and print key and value of a pair.

To compile and run the code, execute the following command:

javac -cp .:vavr-0.10.3.jar PairsInJava.java && java -cp .:vavr-0.10.3.jar PairsInJava

Implement Apache Commons Library

In this step, we will learn how to use MutablePair and ImmutablePair classes from the Apache Commons library to create and manipulate pairs. Add the following code to your PairsInJava.java file:

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

public class PairsInJava {
    public static void main(String[] args) {
        MutablePair<String, Integer> p1 = new MutablePair<>("apple", 1);
        ImmutablePair<String, Integer> p2 = new ImmutablePair<>("banana", 2);

        System.out.println("p1=" + p1.getLeft() + "," + p1.getRight());
        System.out.println("p2=" + p2.getLeft() + "," + p2.getRight());

        p1.setLeft("orange");
        p1.setRight(3);

        System.out.println("new p1=" + p1.getLeft() + "," + p1.getRight());

        // cannot set values for immutable pair
        // p2.setLeft("kiwi");

        p2 = p2.withLeft("kiwi");

        System.out.println("new p2=" + p2.getLeft() + "," + p2.getRight());
    }
}

In the code above, we use MutablePair and ImmutablePair classes from the Apache commons library to create pairs and then modify their key and value.

To compile and run the code, execute the following command:

javac -cp .:commons-lang3-3.13.0.jar PairsInJava.java && java -cp .:commons-lang3-3.13.0.jar PairsInJava

Summary

Pairs are a simple way to store two data items that have a mapping between them. In this lab, we have used different classes and methods to implement pairs in Java. Some of the popular ways are using external libraries like Apache Commons or the Vavr library, using the inbuilt JavaFX Pair class, creating a custom pair class, and using object arrays.

Other Java Tutorials you may like