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