Java元组-迭代



每个元组都实现了Iterable接口,并且可以类似于集合的方式迭代。

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

示例

让我们了解下Java元组的实际应用。这里我们将看到如何迭代元组。

C:\>JavaTuples中创建一个名为TupleTester的java类文件。

文件:TupleTester.java

package com.tutorialspoint;
import org.javatuples.Quartet;
import org.javatuples.Triplet;
public class TupleTester {
   public 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);
   }
}

验证结果

使用如下所示的javac编译器编译类 -

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

现在运行TupleTester查看结果 -

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

输出

验证输出

Test1 5 Test2 
[Test1, 5, Test2]
a b c d 
Quartet:[a, b, c, d]
广告