在 Java 中迭代 KeyValue 元組


要迭代 Java 中的 KeyValue 元組,請使用 Iterable 並使用 for 迴圈對其進行迭代。讓我們首先看看在 JavaTuples 中需要什麼。要使用 JavaTuples 中的 KeyValue 類,您需要匯入以下包

import org.javatuples.KeyValue;

注意:下載 JavaTuples Jar 庫來執行 JavaTuples 程式。如果您使用的是 Eclipse IDE,請右鍵單擊 專案 → 屬性 → Java 構建路徑 → 新增外部 JAR 並上傳下載的 JavaTuples jar 檔案。參考以下指南瞭解執行 JavaTuples 的所有步驟

步驟: 如何在 Eclipse 中執行 JavaTuples 程式

以下是如何在 Java 中迭代 KeyValue 元組的示例

示例

import org.javatuples.KeyValue;
public class Demo {
   public static void main(String[] args) {
      KeyValue<Integer, String> kValue = KeyValue.with(77, "Rank");
      System.out.println("Iterating through the values of the KeyValue Tuple = ");
      for (Object ele : kValue) System.out.println(ele);
      boolean res = kValue.contains("Rank");
      System.out.println("Does the value exist in the Tuple? = "+res);
   }
}

輸出

Iterating through the values of the KeyValue Tuple =
77
Rank
Does the value exist in the Tuple? = true

更新日期: 30-Jul-2019

391 瀏覽量

開啟你的 職業生涯

完成該課程並獲得認證

開始行動
廣告