Returning Multiple Values in Java Using Apache Commons Lang
Introduction
In the world of Java development, one common challenge developers frequently encounter is the need to return multiple values from a method. The traditional approach often involves creating custom classes or using collections like maps to store these values. While functional, these methods can lead to bloated and complex code that is difficult to maintain and understand.
To address this issue, the Apache Commons Lang library offers a streamlined solution. By leveraging the Pair
and Triple
classes provided by this library, developers can return two or three values from a method in a clear and concise manner. This not only simplifies the code but also enhances readability and maintainability.
In this tutorial, we will explore how to set up the Apache Commons Lang library and use its Pair
and Triple
classes to return multiple values from a method. We will also delve into practical examples, such as returning order and shipment details in an e-commerce application, to demonstrate the utility of these classes in real-world scenarios.
Using Triple to Return Three Values
In software development, it's common to encounter scenarios where you need to return multiple values from a method. While returning two values can be handled using the Pair
class, sometimes you need to return three values. This is where the Triple
class from Apache Commons Lang comes in handy.
What is the Triple Class?
The Triple
class is a part of the Apache Commons Lang library and allows you to encapsulate three objects in a single returnable entity. This can be particularly useful for methods that need to return a set of three related values.
How to Use the Triple Class
To use the Triple
class, you first need to include the Apache Commons Lang library in your project. Once that's set up, you can create a Triple
object and use it to return three values from a method.
Here's a step-by-step guide:
-
Add Apache Commons Lang to Your Project
Make sure you have Apache Commons Lang in your project's dependencies. You can add it via Maven or Gradle:
Maven
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency>
Gradle
implementation 'org.apache.commons:commons-lang3:3.12.0'
-
Create a Triple Object
Once you have the library set up, you can create a
Triple
object. Here is an example of how to do that:import org.apache.commons.lang3.tuple.Triple; public class Example { public static Triple<String, Integer, Boolean> getDetails() { String name = "John Doe"; Integer age = 30; Boolean isActive = true; return Triple.of(name, age, isActive); } }
-
Accessing the Values
You can access the values stored in the
Triple
object using thegetLeft()
,getMiddle()
, andgetRight()
methods:Triple<String, Integer, Boolean> details = Example.getDetails(); String name = details.getLeft(); Integer age = details.getMiddle(); Boolean isActive = details.getRight(); System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Active: " + isActive);
Practical Use Case: E-Commerce Application
Let's consider a practical example where you might need to return three values. In an e-commerce application, you might want to return order details, shipment details, and payment details from a method.
Here's how you can do it:
import org.apache.commons.lang3.tuple.Triple;
public class OrderService {
public static Triple<Order, Shipment, Payment> getOrderDetails(int orderId) {
// Fetch order details
Order order = fetchOrder(orderId);
// Fetch shipment details
Shipment shipment = fetchShipment(orderId);
// Fetch payment details
Payment payment = fetchPayment(orderId);
return Triple.of(order, shipment, payment);
}
private static Order fetchOrder(int orderId) {
// Logic to fetch order details
return new Order(orderId, "Product XYZ", 2);
}
private static Shipment fetchShipment(int orderId) {
// Logic to fetch shipment details
return new Shipment(orderId, "12345", "In Transit");
}
private static Payment fetchPayment(int orderId) {
// Logic to fetch payment details
return new Payment(orderId, "Credit Card", 100.0);
}
}
In this example, the getOrderDetails
method returns a Triple
containing an Order
, Shipment
, and Payment
object. This allows you to easily return and handle multiple related values from a single method.
By using the Triple
class, you can simplify your code and make it more readable and maintainable. Whether you're working on an e-commerce application or any other project, the Triple
class can be a valuable tool in your development toolkit.
Immutable vs Mutable Pairs and Triples
In the Apache Commons Lang library, the Pair
and Triple
classes provide a convenient way to return multiple values from a method. These classes come in two varieties: immutable and mutable. Understanding when to use each type can help you write cleaner, more maintainable code.
Immutable Pairs and Triples
Immutable pairs and triples are designed such that their values cannot be changed once they are set. This immutability can be particularly useful in scenarios where you need to ensure that the data remains consistent and unaltered throughout its lifecycle.
Example Usage
Consider an e-commerce application where you need to return both order details and shipment details from a method. Using an immutable pair ensures that once the order and shipment details are set, they cannot be modified inadvertently.
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
public class OrderService {
public Pair<Order, Shipment> getOrderAndShipmentDetails(String orderId) {
Order order = getOrderById(orderId); // Assume this method fetches order details
Shipment shipment = getShipmentByOrderId(orderId); // Assume this method fetches shipment details
return new ImmutablePair<>(order, shipment);
}
}
In this example, ImmutablePair
is used to return both the Order
and Shipment
objects. Since the pair is immutable, the values cannot be changed after they are set.
Mutable Pairs and Triples
Mutable pairs and triples, on the other hand, allow their values to be changed after they are set. This can be useful in scenarios where the data might need to be updated or modified after the initial creation.
Example Usage
Imagine a scenario where you initially set the order and shipment details but might need to update the shipment details later based on new information.
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
public class OrderService {
public Pair<Order, Shipment> getOrderAndShipmentDetails(String orderId) {
Order order = getOrderById(orderId); // Assume this method fetches order details
Shipment shipment = getShipmentByOrderId(orderId); // Assume this method fetches shipment details
MutablePair<Order, Shipment> pair = new MutablePair<>(order, shipment);
// Later in the code, update the shipment details
Shipment updatedShipment = getUpdatedShipmentDetails(orderId); // Assume this fetches updated shipment details
pair.setRight(updatedShipment);
return pair;
}
}
In this example, MutablePair
is used to allow the shipment details to be updated after the pair is initially created.
When to Use Immutable vs Mutable
- Immutable Pairs and Triples: Use these when you need to ensure that the data remains unchanged after it is set. This is particularly useful for data integrity and thread safety.
- Mutable Pairs and Triples: Use these when you anticipate that the data might need to be updated or modified after the initial creation. This provides flexibility but should be used with caution to avoid unintended side effects.
Conclusion
Choosing between immutable and mutable pairs and triples in Apache Commons Lang depends on your specific use case. Immutable pairs and triples offer data integrity and thread safety, while mutable pairs and triples provide flexibility for scenarios where data updates are necessary. By understanding the differences and appropriate use cases for each, you can write cleaner, more maintainable Java code.
Conclusion
In this tutorial, we explored how to effectively return multiple values from a method in Java using the Apache Commons Lang library. By leveraging the Pair
and Triple
classes, we can simplify our code and make it more readable and maintainable. Here are the key takeaways:
-
Simplifying Code with Apache Commons Lang: Instead of creating complex custom classes or using collections like maps, the
Pair
andTriple
classes offer a straightforward way to return multiple values from a method. This approach reduces code complexity and enhances readability. -
Usage of Pair and Triple: The
Pair
class allows for returning two values, while theTriple
class extends this functionality to three values. These classes are particularly useful in scenarios where you need to return linked objects, such as order and shipment details in an e-commerce application. -
Immutable vs Mutable: By default,
Pair
andTriple
are immutable, ensuring that the returned values cannot be modified. However, if mutability is required, the Apache Commons Lang library also providesMutablePair
andMutableTriple
classes. -
Real-World Applications: The tutorial demonstrated practical examples, such as returning order details along with shipment and payment details. These examples highlight how
Pair
andTriple
can be used to handle related data more efficiently.
Using Apache Commons Lang for returning multiple values not only simplifies your code but also improves its quality and efficiency. It allows developers to write more concise and understandable code, making it easier to maintain and extend. We hope this tutorial has provided you with valuable insights into using Pair
and Triple
in your Java projects.