Java 程式可將 Map 的內容轉換為列表


Map 類的物件包含鍵值對。可以將它轉換為兩個列表物件,一個包含鍵值,另一個單獨包含對映值。

將對映轉換為列表 -

示例

import java.util.HashMap;
import java.uitl.ArrayList;
import java.util.Map;

public class MapTohashMap {
   public static void main(String args[]){
      Map<Integer, String> myMap = new HashMap<>();
      myMap.put(1, "Java");
      myMap.put(2, "JavaFX");
      myMap.put(3, "CoffeeScript");
      myMap.put(4, "TypeScript");

      ArrayList<Integer> keyList = new ArrayList<Integer>(myMap.keySet());
      ArrayList<String> valueList = new ArrayList<String>(myMap.values());

      System.out.println("contents of the list holding keys the map ::"+keyList);
      System.out.println("contents of the list holding values of the map ::"+valueList);
   }
}

輸出

contents of the list holding keys the map::[1, 2, 3, 4]
contents of the list holding values of the map::[Java, JavaFX, CoffeeScript, Typescript]

更新於: 31-5-2024

30 千次以上瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.