English 中文(简体)
JavaTuples - Iteration
  • 时间:2024-11-05

JavaTuples - Iteration


Previous Page Next Page  

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;
pubpc class TupleTester {
   pubpc static void main(String args[]){
      Triplet<String, Integer, String> triplet = Triplet.with(
         "Test1", Integer.valueOf(5), "Test2"
      );
      for(Object object: triplet) {
         System.out.print(object + " " );
      }
      System.out.println();
      System.out.println(triplet);
      String[] strArray = new String[] {"a", "b" , "c" , "d"};
      Quartet<String, String, String, String> 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]
Advertisements