Tuple are fundamental data structures found in many programming languages. In this article, we will delve into what tuples are, their various use cases, and explore how they can be implemented in Java. We will also discuss the absence of tuples in the core Java libraries and introduce a custom Tuple class for practical use.
What are Tuples?
A tuple is an ordered collection of elements that can be of different data types. Unlike arrays or lists, tuples can store a heterogeneous set of values, making them versatile data structures. Elements within a tuple are typically accessed by their position or index rather than a key, unlike dictionaries or maps.Use Cases of Tuples
- Multiple Return Values: Tuples are often used to return multiple values from a function or method in situations where creating a custom class or struct would be overkill.
- Grouping Data: Tuples can group related data that doesn't warrant the definition of a new class. For instance, storing latitude and longitude coordinates.
- Data Transformation: Tuples can be employed in data transformation pipelines to represent intermediate results.
Tuple class in Core Java?
There are languages that originally have the tuples data structure. For example, Python, Haskell, Ruby, Rust, Kotlin, and Go have built-in data types for tuples. Core Java does not provide a built-in Tuple class or library while you can use arrays or collections to simulate tuples, it's not as elegant as using dedicated Tuple classes or libraries. Java does not have built-in tuples for several reasons:- Java originally focused on objects rather than primitive data types. Tuples can be considered a kind of object, but they have some differences, such as being immutable.
- Java already has other data structures that can be used to store multiple values, such as lists and arrays.
External Libraries for Tuples
To use tuples effectively in Java, developers often turn to external libraries such as:- Apache Commons Lang: Java Apache Commons Pairs is a library that provides a variety of utility classes for working with pairs of objects. It includes both mutable and immutable pairs, as well as pairs that can store different types of objects.
- javatuples: A library dedicated to tuples with a wide range of tuple types. JavaTuples is a powerful library that provides a wide range of tuple types for Java developers. JavaTuples simplifies working with tuples by offering pre-defined classes for tuples of various arities (number of components). JavaTuples streamlines tuple creation, manipulation, and pattern matching, making it an excellent choice when you need to work with tuples in your Java projects.
Creating a Custom Tuple Class
For practicality, let's create a simple Tuple class in Java and use it to store and retrieve values:
//custom javatuples class example
public class CustomTuple<A, B> {
private A first;
private B second;
//constructor of javatuples class
public CustomTuple(A first, B second) {
this.first = first;
this.second = second;
}
public A getFirst() {
return first;
}
public void setFirst(A first) {
this.first = first;
}
public B getSecond() {
return second;
}
public void setSecond(B second) {
this.second = second;
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
}
In this example, we’ve created a CustomTuple class that takes two generic type parameters A and B. It has getter and setter methods for accessing and modifying the elements of the tuple. The toString() method is overridden to provide a string representation of the tuple. And here is the example of using CustomTuple class:
public class CustomTupleExample {
public static void main(String[] args) {
// Create a custom tuple of String and Integer
CustomTuple<String, Integer> customTuple = new CustomTuple<>("Hello", 42);
// Access elements of the javatuples
String first = customTuple.getFirst();
Integer second = customTuple.getSecond();
// Print the tuple
System.out.println("Tuple: " + customTuple);
// Modify the elements of the tuple
customTuple.setFirst("World");
customTuple.setSecond(99);
// Print the modified tuple
System.out.println("Modified Tuple: " + customTuple);
}
}
The output of this program is here:
Tuple: (Hello, 42)
Modified Tuple: (World, 99)
Let’s have one more example of using a custom tuple class.
public class CustomTupleExample {
public static void main(String[] args) {
// Create a list of custom tuples to represent people's names and ages
CustomTuple<String, Integer> person1 = new CustomTuple<>("Johnny", 11);
CustomTuple<String, Integer> person2 = new CustomTuple<>("Ivy", 13);
CustomTuple<String, Integer> person3 = new CustomTuple<>("Rick", 12);
// Print the information for each person
System.out.println("Person 1: " + person1);
System.out.println("Person 2: " + person2);
System.out.println("Person 3: " + person3);
// Update the age of Person 1
person1.setSecond(12);
// Print the updated information for Person 2
System.out.println("Updated Person 2: " + person2);
}
}
In this example, we create a list of custom tuples, each representing a person's name (String) and age (Integer). We then print the information for each person and update the age of one of them. This demonstrates how a custom Tuple class can be used to store and manipulate pairs of data.
The output of this program is here:
Person 1: (Johnny, 11)
Person 2: (Ivy, 13)
Person 3: (Rick, 12)
Updated Person 2: (Ivy, 13)
Sure, we can realize triplets and any other similar data structure.
public class Triplet<A, B, C> {
private final A first;
private final B second;
private final C third;
public Triplet(A first, B second, C third) {
this.first = first;
this.second = second;
this.third = third;
}
public A getFirst() {
return first;
}
public B getSecond() {
return second;
}
public C getThird() {
return third;
}
@Override
public String toString() {
return "(" + first + ", " + second + ", " + third + ")";
}
}
One more example: convert tuple to array
Let’s modify our CustomTuple class adding in it one simple method to convert tuple to array of objects. Here’s our method:
//custom javatuples class example
public class CustomTuple<A, B> {
private A first;
private B second;
//constructor of javatuples class
public CustomTuple(A first, B second) {
this.first = first;
this.second = second;
}
public A getFirst() {
return first;
}
public void setFirst(A first) {
this.first = first;
}
public B getSecond() {
return second;
}
public void setSecond(B second) {
this.second = second;
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
public Object[] toArray() {
return new Object[]{first, second};
}
}
Here is an example of using this method:
import java.util.Arrays;
public class CustomTupleExample {
public static void main(String[] args) {
// Create a list of custom tuples to represent people's names and ages
CustomTuple<String, Integer> tuple = new CustomTuple<>("Johnny", 11);
// Convert the tuple to an array
Object[] array = tuple.toArray();
// Print the array
System.out.println(Arrays.toString(array));
}
}
The output is:
[Johnny, 11]
GO TO FULL VERSION