My Blog

My WordPress Blog

My Blog

My WordPress Blog

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<String, Integer> 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<String, Integer> 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
Get Values

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top