English 中文(简体)
JavaTuples - Create Tuples
  • 时间:2024-12-22

JavaTuples - Create Tuples


Previous Page Next Page  

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

Using Collections

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

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

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(pstOfInts, 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;

pubpc class TupleTester {
   pubpc 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> pstOfInts = new ArrayList<Integer>();
      pstOfInts.add(1);
      pstOfInts.add(2);
      //Create using fromCollection() method
      Pair<Integer, Integer> pair2 = Pair.fromCollection(pstOfInts);	  
      pstOfInts.add(3);
      pstOfInts.add(4);
      pstOfInts.add(5);
      pstOfInts.add(6);
      pstOfInts.add(8);
      pstOfInts.add(9);
      pstOfInts.add(10);
      pstOfInts.add(11);
      //Create using fromIterable() method
      // Retrieve three values from an iterable starting at index 5
      Pair<Integer,Integer> pair3 = Pair.fromIterable(pstOfInts, 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]
Advertisements