Javatuples 简明教程
JavaTuples - Checking Elements
每个元组都提供了公用方法来以类似于集合的方式检查其元素。
Each tuple provides utility methods to check their elements in similar fashion as collection.
-
contains(element) − checks if element is present or not.
-
containsAll(collection) − checks if elements are present or not.
-
indexOf(element) − returns the index of first element if present otherwise -1.
-
lastIndexOf(element) − returns the index of last element if present otherwise -1.
Pair<String, Integer> pair = Pair.with("Test", Integer.valueOf(5));
boolean isPresent = pair.contains("Test");
Example
我们来看一下 JavaTuples 的实际应用。我们将会看到如何检查元组中的元素。
Let’s see JavaTuples in action. Here we’ll see how to check elements in a tuple.
在 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;
public class TupleTester {
public static void main(String args[]){
Quartet<String, Integer, String, String> quartet = Quartet.with(
"Test1", Integer.valueOf(5), "Test3", "Test3"
);
System.out.println(quartet);
boolean isPresent = quartet.contains(5);
System.out.println("5 is present: " + isPresent);
isPresent = quartet.containsAll(List.of("Test1", "Test3"));
System.out.println("Test1, Test3 are present: " + isPresent);
int indexOfTest3 = quartet.indexOf("Test3");
System.out.println("First Test3 is present at: " + indexOfTest3);
int lastIndexOfTest3 = quartet.lastIndexOf("Test3");
System.out.println("Last Test3 is present at: " + lastIndexOfTest3);
}
}
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