Java Tuple

In this Java tuple tutorial, we will learn about Tuples – a generic data structure and how we can use tuples in a Java program. Tuples, by default, are not part of the Java programming language as a data structure so we will use one nice third-party library javatuples for it.

1. What is a Tuple?

A tuple can be seen as an ordered collection of objects of different types. These objects do not necessarily relate to each other in any way, but collectively they will have some meaning.

For example, ["Sajal Chakraborty," "IT Professional," 32] can be a tuple where each value inside the tuple does not have any relation, but this whole set of values can have some meaning in the application.

Let’s see some more Java tuple examples.

["Java", 1.8, "Windows"]

["Alex", 32, "New York", true]

[3, "Alexa", "howtodoinjava.com", 37000]

2. Tuples in Java

By default, Java doesn’t have any inbuilt data structure to support tuples. Whenever required, we can create a class that can act like a tuple.

Also, in Java, part of the tuple functionality can be written using List or Array but those will not allow us to hold different types of data types by design (Generics). So we can say that heterogeneous tuples using a standard data structure is not possible in Java.

3. Javatuples Library

3.1. Maven

The javatuples library is present in the Maven central repo, and we can add this dependency to use the library. Find the latest version from this link.

<dependency>
    <groupId>org.javatuples</groupId>
    <artifactId>javatuples</artifactId>
    <version>1.2</version>
</dependency>

3.2. Core Classes

Javatuples support tuples of size up to '10' and for each size, it has provided a tuple implementation like below.

  • Unit (one element)
  • Pair (two elements)
  • Triplet (three elements)
  • Quartet (four elements)
  • Quintet (five elements)
  • Sextet (six elements)
  • Septet (seven elements)
  • Octet (eight elements)
  • Ennead (nine elements)
  • Decade (ten elements)

On top of the above classes, it provides two more classes for easy representation of pairs. Those are mostly the same as Pair but have more verbose syntax.

  • KeyValue
  • LabelValue

4. Operations On Tuples

4.1. Creating a Tuple

4.1.1. Factory Methods

Tuples objects are constructed by the provided factory method with() from each tuple class. For example to create a tuple of Pair we can use.

Pair<String, Integer> pair = Pair.with("Sajal", 12);

Quartet<String, Integer, String, Double> quartet1 = Quartet.with("A1",1,"A3",2.3);

4.1.2. Constructor

We can also use the constructor of Pair.

Pair<String, Integer> person = new Pair<>("Sajal", 12);

4.1.3. From Collection or Iterable

We can create tuples from a Collection or Iterable, provided that the collection has the exact number of objects as the items in the tuple.

In this case, please remember that the number of items in the collection should match the type of tuple that we want to create.

//Collection of 4 elements will create Quartet
List<String> listOf4Names = Arrays.asList("A1","A2","A3","A4");
 
Quartet<String, String, String, String> quartet = Quartet.fromCollection(listOf4Names);
 
System.out.println(quartet);
 
//Create a pair with items starting from the specified index.
List<String> listOf4Names = Arrays.asList("A1","A2","A3","A4");
 
Pair<String, String> pair1 = Pair.fromIterable(listOf4Names, 2);
 
System.out.println(pair1);

Program output.

[A1, A2, A3, A4]
[A3, A4]

Similarly, we can create objects in any tuple class based on our requirements.

4.2. Getting Values from Tuple

4.2.1. getValue() Methods

We can get the values from the tuples by using its indexed getValueX() methods where 'X' denotes the element position inside the tuple. For example, getValue0(), getValue1() etc.

Pair<String, Integer> pair = Pair.with("Sajal", 12);
 
System.out.println("Name : " + pair.getValue0());
System.out.println("Exp : " + pair.getValue1());

Program output.

Name : Sajal
Exp : 12

Please note that these getValue() methods are type-safe. It means the compiler already knows the method return type based on the element values used to initialize the tuple.

4.2.2. getValue(int index) Method

Tuples have another method getValue(int index) which is not type-safe. So we need to cast the value to the expected type when we are assigning to a variable.

Pair<String, Integer> pair = Pair.with("Sajal", 12);
 
System.out.println("Name : " + pair.getValue(0));
System.out.println("Exp : " + pair.getValue(1));

Program output.

Name : Sajal
Exp : 12

Classes KeyValue and LabelValue have methods as getKey()/getValue() and getLabel()/getValue(), respectively.

4.3. Setting Values in Tuple

We can set values in tuples after they are created. We can do this by setAtX() method where 'X' is the index position where we want to set value.

Pair<String, Integer> pair = Pair.with("Sajal", 12);
         
//Modify the value
Pair<String, Integer> modifiedPair = pair.setAt0("Kajal");
 
System.out.println(pair);
System.out.println(modifiedPair);

Program output.

[Sajal, 12]
[Kajal, 12]

Please notice that tuples are immutable. So setAt() method returns same type of tuple with modified value. Original tuple is unchanged.

4.4. Adding and Removing Values

4.4.1. add() Method

We can also add elements in Tuple, which will return a new tuple type matching the number of elements. For example, if we add value to an element to a Pair then we will get a Triplet object in return.

A new element is added at the end of the tuple.

Pair<String, Integer> pair = Pair.with("Sajal", 12);
         
Triplet<String, Integer, String> triplet = pair.add("IT Professional");
 
System.out.println(pair);
System.out.println(triplet);

Program output.

[Sajal, 12]
[Sajal, 12, IT Professional]

We can add one tuple object to another tuple as well. It will return the type of Tuple based on the number of elements present after addition.

Triplet<String, String, String> triplet = Triplet.with("Java", "C", "C++");
Quartet<String, String, String, String> quartet = triplet.addAt1("Python");
 
Septet septet = quartet.add(triplet);   //3 + 4 = 7
 
System.out.println(triplet);
System.out.println(quartet);
System.out.println(septet);

Program output.

[Java, C, C++]
[Java, Python, C, C++]
[Java, Python, C, C++, Java, C, C++]

4.4.2. addAt() Method

By default, new elements are added at the end of the tuple. But we can also add elements in other positions of the tuple by using the addAtX() methods.

Triplet<String, String, String> triplet = Triplet.with("Java", "C", "C++");
Quartet<String, String, String, String> quartet = triplet.addAt1("Python");
 
System.out.println(triplet);
System.out.println(quartet);

Program output.

[Java, C, C++]
[Java, Python, C, C++]

4.5. Converting Tuple to Collection or Array

Each tuple class provides asList() and toArray() methods which returns List and Array respectively.

//Convert to list
Quartet<String, Integer, String, Double> quartet1 = Quartet.with("A1",1,"A3",2.3);
 
List<Object> quartletList = quartet1.toList();
 
System.out.println(quartletList);
 
//Convert to array
Object[] quartletArr = quartet1.toArray();
 
System.out.println(Arrays.toString(quartletArr));

Program output.

[A1, 1, A3, 2.3]
[A1, 1, A3, 2.3]

Please note here that tuple can contain heterogeneous types so resulting type will be of List<Object> or Object[] accordingly.

4.6. Iterating over Tuple Values

All tuple classes implement the Iterable interface so they can be iterated in the same way as collections or arrays.

Quartet<String, Integer, String, Double> quartet1 = Quartet.with("A1",1,"A3",2.3);
 
for(Object obj : quartet1) {
    System.out.println(obj);
}

Program output.

A1
1
A3
2.3

4.7. More Tuple Operations

All tuple class has the following utility methods like collection, and we can use those as per our requirement.

  • contains() – returns true if this tuple contains the specified element.
  • containsAll() – returns true if this tuple contains the all the specified elements.
  • indexOf() – returns the index of the first occurrence of the specified element.
  • lastIndexOf() – returns the index of the last occurrence of the specified element.

Tuples also provide the generic implementation of hashCode(), equals() and compareTo() methods which work fine with wrapper and string classes.

5. Benefits of Tuples

Different types of tuples are:

6. Comparison of Tuples vs Lists/Arrays

A tuple is often compared with List as it looks very much like a list. But they differ in some aspects.

  • A tuple is an object that can contain heterogeneous data. Lists are designed to store elements of a single type.
  • Out of all data structures, a tuple is considered to be the fastest, and they consume the least amount of memory.
  • While array and list are mutable which means you can change their data value and modify their structures, a tuple is immutable.
  • Like an array, a tuple is also fixed in size. That is why tuples aim to replace arrays completely as they are more efficient in all parameters.
  • If you have a dataset that will be assigned only once in a lifetime and its value should not change again, we need a tuple.

7. Conclusion

In this Java tuple tutorial, we have seen how we can use tuples in java with javatuple library. So if you face any requirement of a data structure that stores a fixed number of heterogeneous elements, you can use this library.

This library is straightforward, easy to use, and provides good performance.

Happy Learning !!

Download Sourcecode

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode