Open In App

JavaTuples | Introduction

Tuple

The word “tuple” means “a data structure consisting of multiple parts”. Hence Tuples can be defined as a data structure that can hold multiple values and these values may/may not be related to each other. Example:
[Geeks, 123, *@]
In this example, the values in the tuple are not at all related to each other. “Geeks” is a word that has a meaning. “123” are numbers. While “&#*@” are just some bunch of special characters. Hence the values in a tuple might or might not be related to each other.

JavaTuple

JavaTuples is a Java library that offers classes, functions and data structures to work with tuples. It is one of the simplest java library ever made. JavaTuples offers following classes to work with : Note: To run the JavaTuples program, org.javatuples library needs to be added in the IDE. The IDE can be Netbeans, Eclipse, etc. Download JavaTuples Jar library here. To add a library in Netbeans, refer this. The basic characteristics of JavaTuples are:

Why to prefer JavaTuples over Lists/Arrays?

Think of a scenario where you want to store the details of a student in just one entity, like Name, Roll Number, Father’s Name, Contact Number. Now the most common approach that strikes the mind is to construct a data structure that would take the fields as required. This is where Tuples come into play. With Tuples, any separate data structure need not to be created. Instead, for this scenario, a Quartet<A, B, C, D> can be simply used. Therefore, common data structures like List, Array : Whereas, Tuples :
NthTuple<type 1, type 2, .., type n> nthTuple = new NthTuple
                <type 1, type 2, .., type n>(value 1, value 2, .., value n);
nthTuple = nthTuple.setAtX(val);
Example:
Pair<Integer, String> pair = new Pair<Integer, String>(
                            Integer.valueOf(1), "Geeks");
   
pair = pair.setAt1("For"); // This will return a pair (1, "For")
   
Sextet<Integer, String, Integer, String, Integer, String> sextet
    = new Sextet<Integer, String, Integer, String, Integer, String>(
                                        Integer.valueOf(1), "Geeks",
                                        Integer.valueOf(2), "For",
                                        Integer.valueOf(3), "Geeks"
                                        );
   
// This will return sextet (1, "Geeks", 2, "For", 3, "Everyone")
Sextet<Integer, String, Integer, String, Integer, String> otherSextet
    = sextet.setAt5("Everyone");

                    

Iterating JavaTuple values

All tuple classes in javatuples implement the Iterable<Object> interface. It means that they can be iterated in the same way as collections or arrays. Example:
Triplet<String, Integer, Double> triplet = ...... 
  
for (Object value : tuple)
{
    ...
}

                    

Article Tags :