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.