获取 Java Pair 类 Tuple 中的值

java 8object oriented programmingprogramming更新于 2025/3/9 15:52:17

使用 getValueX() 方法从 Java 中特定索引处的 Pair Tuple 类中获取值。例如,getValue0()。

首先让我们看看使用 JavaTuples 需要什么。要使用 JavaTuples 中的 Pair 类,您需要导入以下包 −

import org.javatuples.Pair;

注意 − 下载和运行 JavaTuples 程序的步骤。如果您使用 Eclipse IDE 在 JavaTuples 中运行 Pair 类,则右键单击项目 → 属性 → Java 构建路径 → 添加外部 Jar并上传下载的 JavaTuples jar 文件。

下面是一个例子 −

示例

import org.javatuples.Pair;
public class Demo {
   public static void main(String[] args) {
      Pair < String, String > p1 = Pair.with("One", "Two");
      Pair < String, String > p2 = p1.setAt1("Three");
      System.out.println("Result = " + p2);
      System.out.println("Fetch Value: " + p2.getValue0());
   }
}

输出

Result = [One, Three]
Fetch Value: One

相关文章