Java 程序可将 Map 的内容转换为列表
Map 类的对象包含键值对。可以将它转换为两个列表对象,一个包含键值,另一个单独包含映射值。
将映射转换为列表 -
- 创建一个 Map 对象。
- 使用 put() 方法 将元素作为键值对插入其中
- 创建一个整数类型 ArrayList 来容纳映射的键。在它的构造函数中调用 Map 类的 keySet() 方法。
- 创建一个 ArrayList 的 String 类型来容纳映射的值。在它的构造函数中调用 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