A tuple using JavaTuple classes can be created using multiple options. Following are the examples −
Each tuple class has a with() method with corresponding parameters. For example −
Pair<String, Integer> pair = Pair.with("Test", Integer.valueOf(5)); Triplet<String, Integer, Double> triplet = Triplet.with("Test", Integer.valueOf(5), Double.valueOf(32.1));
Each tuple class has a constructor with corresponding parameters. For example −
Pair<String, Integer> pair = new Pair("Test", Integer.valueOf(5)); Triplet<String, Integer, Double> triplet = new Triplet("Test", Integer.valueOf(5), Double.valueOf(32.1));
Each tuple class has a fromCollection() method with corresponding parameters. For example −
Pair<String, Integer> pair = Pair.fromCollection(listOfTwoElements);
Each tuple class has a fromIterable() method to get elements in generic fashion. For example −
// Retrieve three values from an iterable starting at index 5 Triplet<Integer,Integer,Integer> triplet = Triplet.fromIterable(listOfInts, 5);
Let's see JavaTuples in action. Here we'll see how to create tupels using various ways.
Create a java class file named TupleTester in C:\>JavaTuples.
File: TupleTester.java
package com.howcodex; import java.util.ArrayList; import java.util.List; import org.javatuples.Pair; public class TupleTester { public static void main(String args[]){ //Create using with() method Pair<String, Integer> pair = Pair.with("Test", Integer.valueOf(5)); //Create using constructor() Pair<String, Integer> pair1 = new Pair("Test", Integer.valueOf(5)); List<Integer> listOfInts = new ArrayList<Integer>(); listOfInts.add(1); listOfInts.add(2); //Create using fromCollection() method Pair<Integer, Integer> pair2 = Pair.fromCollection(listOfInts); listOfInts.add(3); listOfInts.add(4); listOfInts.add(5); listOfInts.add(6); listOfInts.add(8); listOfInts.add(9); listOfInts.add(10); listOfInts.add(11); //Create using fromIterable() method // Retrieve three values from an iterable starting at index 5 Pair<Integer,Integer> pair3 = Pair.fromIterable(listOfInts, 5); //print all tuples System.out.println(pair); System.out.println(pair1); System.out.println(pair2); System.out.println(pair3); } }
Verify the result
Compile the classes using javac compiler as follows −
C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/howcodex/TupleTester.java
Now run the TupleTester to see the result −
C:\JavaTuples>java -cp .;javatuples-1.2.jar com.howcodex.TupleTester
Verify the Output
[Test, 5] [Test, 5] [1, 2] [6, 8]