Category: 08. Java Tuples

https://cdn-icons-png.flaticon.com/512/226/226777.png

  • Unit Class

    Introduction

    The org.javatuples.Unit class represents a Tuple with single element.

    Class declaration

    Following is the declaration for org.javatuples.Unit class −

    public final class Unit<A>
       extends Tuple
    
      implements IValue0&lt;A&gt;

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Class constructors

    Sr.No.Constructor & Description
    1Unit(A value0)This creates a Unit Tuple.

    Class Methods

    Sr.No.Method & Description
    1Pair add(Unit tuple)This method returns a Pair tuple.Similarly other methods to add tuples are available e.g. add(Pair tuple) returns Triplet and upto add(Ennead tuple) returns Decade tuple.
    2Pair add(X0 value)This method add a value to the tuple and returns a Pair tuple.Similarly other methods to add values are available e.g. add(X0 value0, X1 value1) returns Triplet and so on upto add() with nine parameters.
    3Pair addAt0(Unit value)This method add a Unit tuple at index 0 and returns a Pair tuple.Similarly other methods to add tuples are available e.g. addAt0(Pair value) returns Triplet and so on upto addAt0(Ennead). Other similar method are addAt1(Unit value) which add a unit at index0 and have similar methods upto addAt1(Ennead).
    4Pair addAt0(X0 value)This method add a value at index 0 and returns a Pair tuple.Similarly other methods to add values are available e.g. addAt0(X0 value0, X1 value1) returns Triplet and so on upto addAt0() with nine parameters. Other similar method are addAt1(X0 value) which add a value at index0 and have similar methods upto addAt1() with nine parameters.
    5static <X> Unit<X> fromArray(X[] array)Create tuple from array.
    6static <X> Unit<X> fromCollection(Collection<X> collection)Create tuple from collection.
    7static <X> Unit<X> fromIterable(Iterable<X> iterable)Create tuple from iterable.
    8static <X> Unit<X> fromIterable(Iterable<X> iterable, int index)Create tuple from iterable, starting from the specified index.
    9int getSize()Return the size of the tuple.
    10A getValue0()Return the value of the tuple.
    11<X> Unit<X> setAt0(X value)Set the value of the tuple.
    12static <A> Unit<A> with(A value0)Create the tuple using given value.

    Methods inherits

    This class inherits methods from the following classes −

    • org.javatuples.Tuple
    • Object

    Example

    Let’s see Unit Class in action. Here we’ll see how to use various methods.

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

    File: TupleTester.java

    package com.tutorialspoint;
    import java.util.ArrayList;
    import java.util.List;
    import org.javatuples.Pair;
    import org.javatuples.Unit;
    public class TupleTester {
       public static void main(String args[]){
    
      Unit&lt;Integer&gt; unit = Unit.with(5);
      System.out.println(unit);
      boolean isPresent = unit.contains(5);
      System.out.println("5 is present: " + isPresent);
      List&lt;Integer&gt; list = new ArrayList&lt;&gt;();
      list.add(1);
      Pair&lt;Integer, String&gt; pair = unit.add("Test");
      System.out.println(pair);
      Integer value = unit.getValue0();
      System.out.println(value);
      Unit&lt;Integer&gt; unit1 = Unit.fromCollection(list);   
      System.out.println(unit1);
    } }

    Verify the result

    Compile the classes using javac compiler as follows −

    C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java
    

    Now run the TupleTester to see the result −

    C:\JavaTuples>java  -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester
    

    Output

    Verify the Output

    [5]
    5 is present: true
    [5, Test]
    5
    [1]
    
  • Checking Elements

    Each tuple provides utility methods to check their elements in similar fashion as collection.

    • contains(element) − checks if element is present or not.
    • containsAll(collection) − checks if elements are present or not.
    • indexOf(element) − returns the index of first element if present otherwise -1.
    • lastIndexOf(element) − returns the index of last element if present otherwise -1.
    Pair<String, Integer> pair = Pair.with("Test", Integer.valueOf(5)); 
    boolean isPresent = pair.contains("Test");
    

    Example

    Let’s see JavaTuples in action. Here we’ll see how to check elements in a tuple.

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

    File: TupleTester.java

    package com.tutorialspoint;
    import java.util.List;
    import org.javatuples.Quartet;
    public class TupleTester {
       public static void main(String args[]){
    
      Quartet&lt;String, Integer, String, String&gt; quartet = Quartet.with(
         "Test1", Integer.valueOf(5), "Test3", "Test3"
      );
      System.out.println(quartet);
      boolean isPresent = quartet.contains(5);
      System.out.println("5 is present: " + isPresent);
      isPresent = quartet.containsAll(List.of("Test1", "Test3"));   
      System.out.println("Test1, Test3 are present: " + isPresent);
      int indexOfTest3 = quartet.indexOf("Test3");
      System.out.println("First Test3 is present at: " + indexOfTest3);
      int lastIndexOfTest3 = quartet.lastIndexOf("Test3");
      System.out.println("Last Test3 is present at: " + lastIndexOfTest3);
    } }

    Verify the result

    Compile the classes using javac compiler as follows −

    C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java
    

    Now run the TupleTester to see the result −

    C:\JavaTuples>java  -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester
    

    Output

    Verify the Output

    [Test1, 5, Test3, Test3]
    5 is present: true
    Test1, Test3 are present: true
    First Test3 is present at: 2
    Last Test3 is present at: 3
    
  • Iteration

    Each tuple implements Iterable interface and can be iterated in similar fashion as collection.

    Pair<String, Integer> pair = Pair.with("Test", Integer.valueOf(5)); 
    for(Object object: Pair){
    	System.out.println(object);
    }
    

    Example

    Let’s see JavaTuples in action. Here we’ll see how to iterate tuples.

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

    File: TupleTester.java

    package com.tutorialspoint;
    import org.javatuples.Quartet;
    import org.javatuples.Triplet;
    public class TupleTester {
       public static void main(String args[]){
    
      Triplet&lt;String, Integer, String&gt; triplet = Triplet.with(
         "Test1", Integer.valueOf(5), "Test2"
      );
      for(Object object: triplet) {
         System.out.print(object + " " );
      }
      System.out.println();
      System.out.println(triplet);
      String&#91;] strArray = new String&#91;] {"a", "b" , "c" , "d"};
      Quartet&lt;String, String, String, String&gt; quartet = Quartet.fromArray(strArray);
      for(Object object: quartet) {
         System.out.print(object + " " );
      }
      System.out.println();
      System.out.println("Quartet:" + quartet);
    } }

    Verify the result

    Compile the classes using javac compiler as follows −

    C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java
    

    Now run the TupleTester to see the result −

    C:\JavaTuples>java  -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester
    

    Output

    Verify the Output

    Test1 5 Test2 
    [Test1, 5, Test2]
    a b c d 
    Quartet:[a, b, c, d]
    
  • Conversion

    Tuple to List/Array

    A tuple can be converted to List/Array but at cost of type safety and converted list is of type List<Object>/Object[].

    List<Object> list = triplet.toList();
    Object[] array = triplet.toArray();
    

    Collection/Array to Tuple

    A collection can be converted to tuple using fromCollection() method and array can be converted to tuple using fromArray() method.

    Pair<String, Integer> pair = Pair.fromCollection(list);
    Quartet<String,String,String,String> quartet = Quartet.fromArray(array); 
    

    If size of array/collection is different than that of tuple, then IllegalArgumentException will occur.

    Exception in thread "main" java.lang.IllegalArgumentException: 
    Array must have exactly 4 elements in order to create a Quartet. Size is 5
       at ...	
    

    Example

    Let’s see JavaTuples in action. Here we’ll see how to convert tuple to list/array and vice versa.

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

    File: TupleTester.java

    package com.tutorialspoint;
    import java.util.List;
    import org.javatuples.Quartet;
    import org.javatuples.Triplet;
    public class TupleTester {
       public static void main(String args[]){
    
      Triplet&lt;String, Integer, String&gt; triplet = Triplet.with(
         "Test1", Integer.valueOf(5), "Test2"
      );
      List&lt;Object&gt; list = triplet.toList();
      Object&#91;] array = triplet.toArray();
      System.out.println("Triplet:" + triplet);
      System.out.println("List: " + list);  
      System.out.println();
      for(Object object: array) {
         System.out.print(object + " " );
      }
      System.out.println();
      String&#91;] strArray = new String&#91;] {"a", "b" , "c" , "d"};
      Quartet&lt;String, String, String, String&gt; quartet = Quartet.fromArray(strArray);
      System.out.println("Quartet:" + quartet);      
    } }

    Verify the result

    Compile the classes using javac compiler as follows −

    C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java
    

    Now run the TupleTester to see the result −

    C:\JavaTuples>java  -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester
    

    Output

    Verify the Output

    Triplet:[Test1, 5, Test2]
    List: [Test1, 5, Test2]
    
    Test1 5 Test2 
    Quartet:[a, b, c, d]
    
  • Remove Elements

    A tuple has removeAtX() methods to remove value at particular index. For example Triplet class has following methods.

    • removeAt0() − remove value at index 0 and return the resulted tuple.
    • removeAt1() − remove value at index 1 and return the resulted tuple.
    • removeAt2() − remove value at index 2 and return the resulted tuple.

    Removing an element returns a new tuple.

    Example

    Let’s see JavaTuples in action. Here we’ll see how to remove value in a tuple.

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

    File: TupleTester.java

    package com.tutorialspoint;
    import org.javatuples.Pair;
    import org.javatuples.Triplet;
    public class TupleTester {
       public static void main(String args[]){
    
      Triplet&lt;String, Integer, String&gt; triplet = Triplet.with(
         "Test1", Integer.valueOf(5), "Test2"
      );
      Pair&lt;String, Integer&gt; pair = triplet.removeFrom2();
      System.out.println("Triplet:" + triplet);
      System.out.println("Pair: " + pair);  
    } }

    Verify the result

    Compile the classes using javac compiler as follows −

    C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java
    

    Now run the TupleTester to see the result −

    C:\JavaTuples>java  -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester
    

    Output

    Verify the Output

    Triplet:[Test1, 5, Test2]
    Pair: [Test1, 5]
    
  • Add Elements

    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.tutorialspoint;
    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&lt;String, Integer&gt; pair = Pair.with("Test", Integer.valueOf(5));   
      Triplet&lt;String, Integer, String&gt; triplet = pair.add("Test2");
      Quartet&lt;String, String, Integer, String&gt; quartet = triplet.addAt1("Test1");
      Quintet&lt;String, Integer, String, String, Integer&gt; 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/tutorialspoint/TupleTester.java
    

    Now run the TupleTester to see the result −

    C:\JavaTuples>java  -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester
    

    Output

    Verify the Output

    Pair: [Test, 5]
    Triplet:[Test, 5, Test2]
    Quartet:[Test, Test1, 5, Test2]
    Quintet:[Test, 5, Test2, Test, 5]
    
  • Set Values

    A tuple has setAtX() methods to set value at particular index. For example Triplet class has following methods.

    • setAt0() − set value at index 0.
    • setAt1() − set value at index 1.
    • setAt2() − set value at index 2.

    Feature

    • Tuples are immutable. Each setAtX() returns a new tuple which is to be used to see the updated value.
    • Type of a position of a tuple can be changed using setAtX() method.

    Example

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

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

    File: TupleTester.java

    package com.tutorialspoint;
    import org.javatuples.Pair;
    public class TupleTester {
       public static void main(String args[]){
    
      //Create using with() method
      Pair&lt;String, Integer&gt; pair = Pair.with("Test", Integer.valueOf(5));   
      Pair&lt;String, Integer&gt; pair1 = pair.setAt0("Updated Value");
      System.out.println("Original Pair: " + pair);
      System.out.println("Updated Pair:" + pair1);
      Pair&lt;String, String&gt; pair2 = pair.setAt1("Changed Type");
      System.out.println("Original Pair: " + pair);
      System.out.println("Changed Pair:" + pair2);
    } }

    Verify the result

    Compile the classes using javac compiler as follows −

    C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java
    

    Now run the TupleTester to see the result −

    C:\JavaTuples>java  -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Output

    Verify the Output

    Original Pair: [Test, 5]
    Updated Pair:[Updated Value, 5]
    Original Pair: [Test, 5]
    Changed Pair:[Test, Changed Type]
    
  • Get Values

    A tuple has getValueX() methods to get values and getValue() a generic method to get value by index. For example Triplet class has following methods.

    • getValue(index) − returns value at index starting from 0.
    • getValue0() − returns value at index 0.
    • getValue1() − returns value at index 1.
    • getValue2() − returns value at index 2.

    Feature

    • getValueX() methods are typesafe and no cast is required, but getValue(index) is generic.
    • A tuple has getValueX() methods upto element count. For example, Triplet has no getValue3() method but Quartet has.
    • Semantic Classes KeyValue and LabelValue has getKey()/getValue() and getLabel()/getValue() instead of getValue0()/getValue1() methods.

    Example

    Let’s see JavaTuples in action. Here we’ll see how to get values from a tuple using various ways.

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

    File: TupleTester.java

    package com.tutorialspoint;
    import org.javatuples.KeyValue;
    import org.javatuples.Pair;
    public class TupleTester {
       public static void main(String args[]){
    
      //Create using with() method
      Pair&lt;String, Integer&gt; pair = Pair.with("Test", Integer.valueOf(5));   
      Object value0Obj = pair.getValue(0);
      Object value1Obj = pair.getValue(1);
      String value0 = pair.getValue0();
      Integer value1 = pair.getValue1();
      System.out.println(value0Obj);
      System.out.println(value1Obj);
      System.out.println(value0);
      System.out.println(value1);  
       KeyValue&lt;String, Integer&gt; keyValue = KeyValue.with(
         "Test", Integer.valueOf(5)
      );
      value0 = keyValue.getKey();
      value1 = keyValue.getValue();
      System.out.println(value0Obj);
      System.out.println(value1Obj);
    } }

    Verify the result

    Compile the classes using javac compiler as follows −

    C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java
    

    Now run the TupleTester to see the result −

    C:\JavaTuples>java  -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Output

    Verify the Output

    Test
    5
    Test
    5
    Test
    5
    
  • Create Tuples

    A tuple using JavaTuple classes can be created using multiple options. Following are the examples −

    Using with() Methods

    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));	
    

    Using Constructor

    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));	
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Using Collections

    Each tuple class has a fromCollection() method with corresponding parameters. For example −

    Pair<String, Integer> pair = Pair.fromCollection(listOfTwoElements);	
    

    Using Iterable

    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);
    

    Example

    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.tutorialspoint;
    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&lt;String, Integer&gt; pair = Pair.with("Test", Integer.valueOf(5));   
      //Create using constructor()
      Pair&lt;String, Integer&gt; pair1 = new Pair("Test", Integer.valueOf(5)); 
      List&lt;Integer&gt; listOfInts = new ArrayList&lt;Integer&gt;();
      listOfInts.add(1);
      listOfInts.add(2);
      //Create using fromCollection() method
      Pair&lt;Integer, Integer&gt; 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&lt;Integer,Integer&gt; 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/tutorialspoint/TupleTester.java
    

    Now run the TupleTester to see the result −

    C:\JavaTuples>java  -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester
    

    Output

    Verify the Output

    [Test, 5]
    [Test, 5]
    [1, 2]
    [6, 8]
    
  • Environment Setup

    Local Environment Setup

    If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Please follow the steps mentioned below to set up the environment.

    Java SE is freely available from the link Download Java. So you download a version based on your operating system.

    Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories −

    Setting up the Path for Windows 2000/XP

    We are assuming that you have installed Java in c:\Program Files\java\jdk directory −

    • Right-click on ‘My Computer’ and select ‘Properties’.
    • Click on the ‘Environment variables’ button under the ‘Advanced’ tab.
    • Now, alter the ‘Path’ variable so that it also contains the path to the Java executable. Example, if the path is currently set to ‘C:\WINDOWS\SYSTEM32’, then change your path to read ‘C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin’.

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Setting up the Path for Windows 95/98/M

    We are assuming that you have installed Java in c:\Program Files\java\jdk directory −

    • Edit the ‘C:\autoexec.bat’ file and add the following line at the end − ‘SET PATH=%PATH%;C:\Program Files\java\jdk\bin’

    Setting up the Path for Linux, UNIX, Solaris, FreeBS

    Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.

    Example, if you use bash as your shell, then you would add the following line to the end of your ‘.bashrc: export PATH=/path/to/java:$PATH’

    Popular Java Editor

    To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −

    • Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
    • Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.
    • Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.

    Download JavaTuples Archie

    Download the latest version of JavaTuples jar file from Maven Repository – JavaTuples. In this tutorial, javatuples-1.2.jar is downloaded and copied into C:\> javatuples folder.

    OSArchive name
    Windowsjavatuples-1.2.jar
    Linuxjavatuples-1.2.jar
    Macjavatuples-1.2.jar

    Set JavaTuples Environment

    Set the JavaTuples environment variable to point to the base directory location where JavaTuples jar is stored on your machine. Assuming, we’ve extracted javatuples-1.2.jar in JavaTuples folder on various Operating Systems as follows.

    OSOutput
    WindowsSet the environment variable JavaTuples to C:\JavaTuples
    Linuxexport JavaTuples=/usr/local/JavaTuples
    Macexport JavaTuples=/Library/JavaTuples

    Set CLASSPATH Variable

    Set the CLASSPATH environment variable to point to the JavaTuples jar location. Assuming, you have stored javatuples-1.2.jar in JavaTuples folder on various Operating Systems as follows.

    OSOutput
    WindowsSet the environment variable CLASSPATH to %CLASSPATH%;%JavaTuples%\javatuples-1.2.jar;.;
    Linuxexport CLASSPATH=$CLASSPATH:$JavaTuples/javatuples-1.2.jar:.
    Macexport CLASSPATH=$CLASSPATH:$JavaTuples/javatuples-1.2.jar:.