如何转换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 $的有效字符串表示形式C $ C>秒。此外,您可以在转换时发生碰撞;例如,
0
和00
都映射到 0L
。
This assumes that all keys are valid string-representations of Long
s. 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());
}
此代码假定您已清理 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.
编辑
我遇到了 Scratch,它只适用于那些类实现 Commons Collection-Utils中的CollectionUtils #iteredCollection(Collection,Transformer)
方法,看起来它可能会做你想要的。集合
。
I came across the Scratch that, it only works for classes that implement CollectionUtils#transformedCollection(Collection, Transformer)
method in Commons Collection-Utils that looks like it might do what you want.Collection
.