Author
Vasyl Malik
Senior Java Developer at CodeGym

Java Tuple

Published in the Java Collections group
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.
However, Java has the ability to use libraries to implement tuples. For example, the Google Guava library provides the Tuple class, which implements immutable tuples. In recent years, there has been a trend towards using tuples in Java. In Java 12, new operators were added for working with tuples, and in Java 17, new methods were added for accessing the elements of a tuple. This could indicate that built-in tuples may be added to Java in the future.

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]

Conclusion

In this article, we've explored what tuples are, discussed their various use cases, and highlighted their absence in core Java. We introduced external libraries for working with tuples and demonstrated how to create and use a custom Tuple class in Java. Tuples offer a convenient way to work with ordered collections of heterogeneous data, filling a niche not entirely addressed by Java's built-in data structures.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION