Javatuples 简明教程
JavaTuples - Conversion
Tuple to List/Array
元组可以转换成 List/Array,但会损失类型安全性,转换后的列表是 List<Object>/Object[] 类型。
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
集合可以使用fromCollection()方法转换成元组,数组可以使用fromArray()方法转换成元组。
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);
如果数组/集合的大小与元组不同,则会发生 IllegalArgumentException。
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
让我们来看看 JavaTuples 的实际应用。这里我们将看到如何将元组转换成列表/数组,反之亦然。
Let’s see JavaTuples in action. Here we’ll see how to convert tuple to list/array and vice versa.
在 C:>JavaTuples 中创建一个名为 TupleTester 的 Java 类文件。
Create a java class file named TupleTester in C:\>JavaTuples.
文件:TupleTester.java
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<String, Integer, String> triplet = Triplet.with(
"Test1", Integer.valueOf(5), "Test2"
);
List<Object> list = triplet.toList();
Object[] 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[] strArray = new String[] {"a", "b" , "c" , "d"};
Quartet<String, String, String, String> quartet = Quartet.fromArray(strArray);
System.out.println("Quartet:" + quartet);
}
}
Verify the result
Verify the result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java
现在运行 TupleTester 查看结果:
Now run the TupleTester to see the result −
C:\JavaTuples>java -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester