Tuple Libraries
Popular Java Tuple Libraries
1. Apache Commons Lang
Apache Commons Lang provides utility classes for tuple-like operations:
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
public class CommonsLangTupleDemo {
public static void main(String[] args) {
// Create a Pair
Pair<String, Integer> user = Pair.of("Alice", 25);
// Create a Triple
Triple<String, String, Integer> employee =
Triple.of("John Doe", "Engineering", 50000);
System.out.println("User: " + user.getLeft() + ", " + user.getRight());
System.out.println("Employee: " + employee.getLeft() +
", " + employee.getMiddle() +
", " + employee.getRight());
}
}
2. Vavr (Functional Java Library)
Vavr offers powerful tuple implementations with functional programming support:
import io.vavr.Tuple2;
import io.vavr.Tuple3;
public class VavrTupleDemo {
public static void main(String[] args) {
// Create a Tuple2
Tuple2<String, Integer> person =
Tuple2.of("Bob", 30);
// Create a Tuple3
Tuple3<String, String, Double> student =
Tuple3.of("Computer Science", "Advanced", 3.8);
System.out.println("Person: " + person._1 + ", " + person._2);
System.out.println("Student: " + student._1 +
", " + student._2 +
", " + student._3);
}
}
Comparison of Tuple Libraries
graph TD
A[Tuple Libraries] --> B[Apache Commons Lang]
A --> C[Vavr]
A --> D[Javatuples]
Library Comparison Table
Feature |
Apache Commons Lang |
Vavr |
Javatuples |
Immutability |
Partial |
Full |
Full |
Max Tuple Size |
Triple |
Up to 8 |
Up to 8 |
Functional Support |
Limited |
Extensive |
Basic |
Performance |
Good |
Moderate |
Good |
3. Javatuples Library
Javatuples provides a comprehensive tuple implementation:
import org.javatuples.Pair;
import org.javatuples.Triplet;
public class JavatupleDemo {
public static void main(String[] args) {
// Create a Pair
Pair<String, Integer> contact =
Pair.with("[email protected]", 1234567890);
// Create a Triplet
Triplet<String, String, Integer> record =
Triplet.with("Sales", "Q3", 250000);
System.out.println("Contact: " + contact.getValue0() +
", " + contact.getValue1());
System.out.println("Record: " + record.getValue0() +
", " + record.getValue1() +
", " + record.getValue2());
}
}
Choosing the Right Library
Consider these factors when selecting a tuple library:
- Project requirements
- Performance needs
- Functional programming support
- Compatibility with existing codebase
Maven Dependencies
Add these to your pom.xml
for respective libraries:
<!-- Apache Commons Lang -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<!-- Vavr -->
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>0.10.4</version>
</dependency>
<!-- Javatuples -->
<dependency>
<groupId>org.javatuples</groupId>
<artifactId>javatuples</artifactId>
<version>1.2</version>
</dependency>
With LabEx, you can experiment with these libraries and find the best fit for your Java projects.