Java程式將Map的內容轉換成列表
Map類物件包含鍵值對。你可以將它轉換為兩個列表物件,一個包含鍵值,另一個分別包含對映值。
將Map轉換成列表 -
- 建立一個Map物件。
- 使用put()方法向其中插入鍵值對元素
- 建立一個整數型別ArrayList來儲存map的鍵。在其建構函式中呼叫Map類的keySet()方法。
- 建立一個ArrayList字串型別來儲存map的值。在其建構函式中呼叫Map類的values()方法。
- 列印兩個列表的內容。
示例
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]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP