如何转换Map< String,String> to Map< Long,String> ? (选项:使用番石榴) [英] How to convert Map<String, String> to Map<Long, String> ? (option : using guava)

查看:653
本文介绍了如何转换Map< String,String> to Map< Long,String> ? (选项:使用番石榴)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Map< String,String> String 键只是数字值,如123我正在获取数值,因为这些值来自我的JSF组件中的UI。我不想更改UI组件的合同。


现在我想根据上面的 Map <创建一个 Map< Long,String> / code>,我在 Maps 类中看到了一些转换方法,但所有方法都专注于转换值而不是关键。


有没有更好的方法将 Map< String,String> 转换为 Map< Long,String> ;

I have a Map<String, String> the String key is nothing but numeric value like "123" etc. I'm getting numeric value because this values are coming from the UI in my JSF component. I don't want to change the contract of UI component.

Now I would like to create a Map<Long, String> based on the above Map, I saw some transform methods in the Maps class but all are focusing on the converting value and not key.

Is there any better way to convert Map<String, String> to Map<Long, String> ?

推荐答案

Java 8的更新

您可以使用流来执行此操作:

You can use streams to do this:

Map<Long, String> newMap = oldMap.entrySet().stream()
  .collect(Collectors.toMap(e -> Long.parseLong(e.getKey()), Map.Entry::getValue));

这假设所有密钥都是 Long 秒。此外,您可以在转换时发生碰撞;例如,000都映射到 0L

This assumes that all keys are valid string-representations of Longs. Also, you can have collisions when transforming; for example, "0" and "00" both map to 0L.

我认为你必须迭代地图:

I would think that you'd have to iterate over the map:

Map<Long, String> newMap = new HashMap<Long, String>();
for(Map.Entry<String, String> entry : map.entrySet()) {
   newMap.put(Long.parseLong(entry.getKey()), entry.getValue());
}

此代码假定您已清理<$ c $中的所有值c> map (所以没有无效的长值)。

This code assumes that you've sanitized all the values in map (so no invalid long values).

我希望有更好的解决方案。

I'm hoping there is a better solution.

编辑

我遇到了 Commons Collection-Utils中的CollectionUtils #iteredCollection(Collection,Transformer) 方法,看起来它可能会做你想要的。 Scratch,它只适用于那些类实现集合

I came across the CollectionUtils#transformedCollection(Collection, Transformer) method in Commons Collection-Utils that looks like it might do what you want. Scratch that, it only works for classes that implement Collection.

这篇关于如何转换Map&lt; String,String&gt; to Map&lt; Long,String&gt; ? (选项:使用番石榴)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆