← Back to list

“Efficient Data Handling in Java: Returning Multiple Objects with Pair"

Introduction

Abhay Pratap Singh · 2024-08-28 18:55 · 5 claps · 4.0 min read
#java #design-thinking #method-writing
Open on Medium ↗
Wiki topics: PRD · Product Design

Photo by Blake Wisz on Unsplash

Photo by Blake Wisz on Unsplash

“Efficient Data Handling in Java: Returning Multiple Objects with Pair"

Introduction

In Java, a common scenario involves returning multiple values from a method. Traditionally, you might use custom classes or collections like arrays or lists. However, the Pair class offers a simpler and more readable way to achieve this. This article explores how to use Pair to return two objects from a method, provides examples, and discusses the pros and cons of this approach.

What is Pair?

Pair is a utility class provided in some Java libraries like JavaFX (javafx.util.Pair). It allows you to store two objects together in a single object. The two objects are referred to as the "key" and the "value."

Where K and V are the types of the objects you want to store in the Pair.

Pair<K, V> pair = new Pair<>(key, value);

Example Usage

Let’s take a deeper dive into how Pair can be used in different scenarios.

  1. Returning Two Related Data Points

If you need to return both the first and last occurrence of a character in a string, Pair<Integer, Integer> can simplify the process.

import javafx.util.Pair;

public class StringUtils {

    public static Pair<Integer, Integer> getFirstAndLastIndex(String input, char target) {
        int firstIndex = input.indexOf(target);
        int lastIndex = input.lastIndexOf(target);
        return new Pair<>(firstIndex, lastIndex);  
    }

    public static void main(String[] args) {
        String input = "hello world";
        Pair<Integer, Integer> indices = getFirstAndLastIndex(input, 'o');
        System.out.println("First Index: " + indices.getKey());
        System.out.println("Last Index: " + indices.getValue());
    }
}
  1. Returning Two Objects from Different Classes

Suppose you have a User object and a Role object, and you want to return both from a method.

Explanation:

getUserWithRole: This method returns a Pair containing a User object and a Role object.

  • Pair<User, Role>: The key is the User, and the value is the Role.
import javafx.util.Pair;

class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{name='" + name + "', age=" + age + "}";
    }
}

class Role {
    private String roleName;

    public Role(String roleName) {
        this.roleName = roleName;
    }

    @Override
    public String toString() {
        return "Role{roleName='" + roleName + "'}";
    }
}

public class UserRoleManager {

    public static Pair<User, Role> getUserWithRole() {
        User user = new User("Alice", 28);
        Role role = new Role("Admin");
        return new Pair<>(user, role);
    }

    public static void main(String[] args) {
        Pair<User, Role> userWithRole = getUserWithRole();
        System.out.println("User: " + userWithRole.getKey());
        System.out.println("Role: " + userWithRole.getValue());
    }
}

Pros and Cons of Using Pair

Using Pair has both advantages and limitations that developers should consider.

Pros:

  1. Simplicity: Using Pair allows you to return two values without creating a custom class, simplifying your code.
  2. Readability: The key-value structure of Pair makes the code more intuitive and easier to understand.
  3. Flexibility: Pair can hold any two types of objects, making it highly versatile.

Cons:

  1. Limited Semantics: Pair does not convey the meaning of the data it holds. Custom classes provide more clarity and context to the data being returned.
  2. Potential Misuse: Overusing Pair can lead to less descriptive code, as developers might use it for complex data structures where custom classes would be more appropriate.
  3. Library Dependency: Not all Java environments come with Pair, meaning you might need to import it from a specific library, which can add unnecessary dependencies to your project.

Pair Implementation libraries:

The Pair class is not part of the standard Java SE library. Instead, it is available in a few different libraries. Here are some of the most commonly used libraries that provide a Pair class:

1. JavaFX (javafx.util.Pair)

  • Library: JavaFX is a set of graphics and media packages that enables you to create rich client applications. It is part of the JDK in Java 8, but from Java 11 onwards, it has been decoupled and must be added as a separate module.
  • Package: javafx.util.Pair
  • Dependency: For Java 11 and above, you need to include the JavaFX library as a dependency in your project.
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-controls</artifactId>
    <version>17.0.2</version>
</dependency>

2. Apache Commons Lang (org.apache.commons.lang3.tuple.Pair)

  • Library: Apache Commons Lang is a popular library that extends the standard Java library with additional functionality, including the Pair class as part of its tuple utilities.
  • Package: org.apache.commons.lang3.tuple.Pair

Dependency: Maven:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

3. Vavr (io.vavr.Tuple2)

  • Library: Vavr (formerly known as Javaslang) is a functional programming library for Java that includes tuples, which can be used as a Pair.
  • Class: Tuple2 is essentially a pair.
  • Package: io.vavr.Tuple2
  • Usage:
import io.vavr.Tuple;
import io.vavr.Tuple2;

Dependency: Maven:

<dependency>
    <groupId>io.vavr</groupId>
    <artifactId>vavr</artifactId>
    <version>0.10.3</version>
</dependency>

Which One to Use?

  • JavaFX: Use javafx.util.Pair if you are already using JavaFX in your project, as it won't require additional dependencies.
  • Apache Commons Lang: If you prefer a lightweight and widely used library, org.apache.commons.lang3.tuple.Pair from Apache Commons Lang is a good choice.
  • Vavr: If you are working with functional programming in Java, io.vavr.Tuple2 provides more functional features and is a good fit for modern Java development.

Example with Apache Commons Lang:

Here’s how you can use the Pair from Apache Commons Lang:

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

public class MathOperations {

    public static Pair<Integer, Double> calculateSumAndAverage(int[] numbers) {
        int sum = 0;
        for (int number : numbers) {
            sum += number;
        }
        double average = (double) sum / numbers.length;
        return Pair.of(sum, average);
    }

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        Pair<Integer, Double> result = calculateSumAndAverage(numbers);
        System.out.println("Sum: " + result.getLeft());
        System.out.println("Average: " + result.getRight());
    }
}

Conclusion

Depending on your project’s needs, you can choose the appropriate Pair implementation. JavaFX’s Pair is useful for simple applications, Apache Commons Lang's Pair is great for general-purpose use, and Vavr's Tuple2 is ideal for functional programming enthusiasts

The Pair class in Java is a useful tool for returning two values from a method, especially when those values are logically related. While it simplifies code and enhances readability, it's important to consider whether a custom class might be more appropriate for complex or domain-specific data. Use Pair wisely to strike a balance between simplicity and clarity in your code


메타데이터
post_id
a9ad32f46ea5
slug
efficient-data-handling-in-java-returning-multiple-objects-with-pair-a9ad32f46ea5
url
https://medium.com/@being-dev-entity/efficient-data-handling-in-java-returning-multiple-objects-with-pair-a9ad32f46ea5
canonical_url
https://medium.com/@being-dev-entity/efficient-data-handling-in-java-returning-multiple-objects-with-pair-a9ad32f46ea5
author_url
https://medium.com/@being-dev-entity
status
ok
fetched_at
2026-07-28 02:41:04