JavaTuples - Add Elements


Advertisements

A tuple has add() method at the end of a tuple and it changes the type of tuple as well. For example adding a element to Triplet tuple will convert it to a Quartet tuple.

Quartet<String,String,String,String> quartet = triplet.add("Test");

A tuple has addAtX() methods as well to add a position at particular index starting from 0.

Quartet<String,String,String,String> quartet = triplet.addAt1("Test");

A tuple can add more than one elements using addAtX() methods.

Quartet<String,String,String,String> quartet = pair.addAt1("Test1", "Test2");

A tuple can add a tuple as well using addAtX() methods.

Quartet<String,String,String,String> quartet = pair.addAt1(pair1);

Example

Let's see JavaTuples in action. Here we'll see how to add values in a tuple using various ways.

Create a java class file named TupleTester in C:\>JavaTuples.

File: TupleTester.java

package com.howcodex;
import org.javatuples.Pair;
import org.javatuples.Quartet;
import org.javatuples.Quintet;
import org.javatuples.Triplet;
public class TupleTester {
   public static void main(String args[]){
      Pair<String, Integer> pair = Pair.with("Test", Integer.valueOf(5));   
      Triplet<String, Integer, String> triplet = pair.add("Test2");
      Quartet<String, String, Integer, String> quartet = triplet.addAt1("Test1");
      Quintet<String, Integer, String, String, Integer> quintet = triplet.add(pair);
      System.out.println("Pair: " + pair);
      System.out.println("Triplet:" + triplet);
      System.out.println("Quartet:" + quartet);
      System.out.println("Quintet:" + quintet);     
   }
}

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

Output

Verify the Output

Pair: [Test, 5]
Triplet:[Test, 5, Test2]
Quartet:[Test, Test1, 5, Test2]
Quintet:[Test, 5, Test2, Test, 5]
Advertisements