如何把map的value转为list_如何将HashMap转换为Java中的List?

HashMap map = new HashMap(); map.put (1, "Mark"); map.put (2, "Tarryn"); List list = new ArrayList(map.values()); for (String s : list) { System.out.println(s); }

假设你有:

HashMap map; // Assigned or populated somehow.

有关值的列表:

List values = new ArrayList(map.values());

有关键的列表:

List keys = new ArrayList(map.keySet());

请注意,键和值的顺序对于HashMap来说是不可靠的; 如果需要在各自的列表中保留键和值位置的一对一对应关系,请使用LinkedHashMap 。

基本上你不应该把问题的答案弄乱,因为这是令人困惑的。

然后你可以指定什么转换的意思,并select一个解决scheme

List keyList = Collections.list(Collections.enumeration(map.keySet())); List valueList = Collections.list(Collections.enumeration(map.values()));

集合接口有3个视图

中的keySet

的entrySet

其他已经回答将Hashmap转换成两个键和值的列表。 它完全正确

我的补充:如何将“键值对”(又名entrySet)转换成列表。

Map m=new HashMap(); m.put(3, "dev2"); m.put(4, "dev3"); List entryList = new ArrayList(m.entrySet()); for (Entry s : entryList) { System.out.println(s); }

ArrayList有这个构造函数。

使用Java 8和Stream Api的解决scheme:

private static List createListFromMapEntries (Map map){ return map.values().stream().collect(Collectors.toList()); }

用法:

public static void main (String[] args) { Map map = new HashMap<>(); map.put(1, "one"); map.put(2, "two"); map.put(3, "three"); List result = createListFromMapEntries(map); result.forEach(System.out :: println); }

如果你只想要迭代你的HashMap,不需要列表:

HashMap map = new HashMap(); map.put (1, "Mark"); map.put (2, "Tarryn"); for (String s : map.values()) { System.out.println(s); }

当然,如果你想在结构上修改你的映射(即不仅仅是改变现有键的值),那么你最好使用“copy to ArrayList”方法,否则你会得到一个ConcurrentModificationExceptionexception。 或者作为一个数组导出:

HashMap map = new HashMap(); map.put (1, "Mark"); map.put (2, "Tarryn"); for (String s : map.values().toArray(new String[]{})) { System.out.println(s); }

如果您想在列表中保持相同的顺序,请说:您的地图看起来像:

map.put(1, "msg1") map.put(2, "msg2") map.put(3, "msg3")

你希望你的列表看起来像

["msg1", "msg2", "msg3"] // same order as the map

你将不得不遍历Map:

// sort your map based on key, otherwise you will get IndexOutofBoundException Map treeMap = new TreeMap(map) List list = new List(); for (treeMap.Entry entry : treeMap.entrySet()) { list.add(entry.getKey(), entry.getValue()); }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值