Javatuples 简明教程
JavaTuples - Create Tuples
可以使用多个选项使用 JavaTuple 类创建元组。以下是示例:
A tuple using JavaTuple classes can be created using multiple options. Following are the examples −
Using with() Methods
每个元组类都有一个带对应参数的 with() 方法。例如:
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
每个元组类都有一个带有相应参数的 fromCollection() 方法。例如:
Each tuple class has a fromCollection() method with corresponding parameters. For example −
Pair<String, Integer> pair = Pair.fromCollection(listOfTwoElements);
Using Iterable
每个元组类都有一个 fromIterable() 方法以通用方式获取元素。例如:
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(listOfInts, 5);
Example
让我们来看看 JavaTuples 在操作中的表现。此处我们将了解使用各种方式创建元组。
Let’s see JavaTuples in action. Here we’ll see how to create tupels using various ways.
在 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.ArrayList;
import java.util.List;
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));
//Create using constructor()
Pair<String, Integer> pair1 = new Pair("Test", Integer.valueOf(5));
List<Integer> listOfInts = new ArrayList<Integer>();
listOfInts.add(1);
listOfInts.add(2);
//Create using fromCollection() method
Pair<Integer, Integer> pair2 = Pair.fromCollection(listOfInts);
listOfInts.add(3);
listOfInts.add(4);
listOfInts.add(5);
listOfInts.add(6);
listOfInts.add(8);
listOfInts.add(9);
listOfInts.add(10);
listOfInts.add(11);
//Create using fromIterable() method
// Retrieve three values from an iterable starting at index 5
Pair<Integer,Integer> pair3 = Pair.fromIterable(listOfInts, 5);
//print all tuples
System.out.println(pair);
System.out.println(pair1);
System.out.println(pair2);
System.out.println(pair3);
}
}
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