What are tuples?
A tuple is an ordered collection of different types of objects that may or may not relate with each other. It can also be seen as a set, in which the values don't relate with each other but together, they make sense in an application. For example: ["James Doe", "IT Professional", 28]
In this example, it is clear that this data is related to a specific employee, that consist his name, profession and age.
Javatuples
In java, to store objects, we have ArrayList, HashMap, Set etc. But when it comes to a situation when we want to store data in the form of tuple, we use java built-in Javatuples classes. Javatuples offers classes to hold upto 10 elements:
In addition with the above classes, KeyValue<A,B> and LabelValue<A,B> also provide functionalites similar to Pair<A,B> for code semantics.
All tuple classes implements the Iterable, Comparable and Serializable interfaces and each of them are immutable and typesafe.
Tuples Common Operations
1. Creating a tuple
Pair<String, String> pair = new Pair<String, String>("John Doe", "Manager");
Another way is,
Pair<String, String> Pair.with("John Doe", "Manager");
2. Retrieve values from a tuple
To retrieve values, getValueX() method is used, where X is to be replace with the position of element inside the tuple.
Pair<String, String> pair = new Pair<String, String>("John Doe", "Manager") System.out.println("Employee Name: "+ pair.getValue0()); System.out.println("Employee Designation: "+ pair.getValue1());
3. Add elements in tuple
Pair<String, String> pair = new Pair<String, String>("John Doe", "Manager"); Triplet<String, String, Integer> triplet = pair.add("30"); //["John Doe", "Manager", 30]
4. Remove elements from tuple
Pair<String, String> pair = new Pair<String, String>("John Doe", "Manager"); Unit<String> unit = pair.removeFrom0();
5. Iteration through tuple
Quartet<String, Integer, Double, String> quartet = Quartet.with("A", 1, 0.1, "B"); for(Object obj : quartet){ System.out.println(obj); } Output: A 1 0.1 B