java 获取哈希图键作为整数数组
我有一个像这样的哈希图
public HashMap <String,People> valueHashMap = new Hashmap();
这里我的哈希图的键是以秒为单位的时间字符串,即我像这样向哈希图添加值
long timeSinceEpoch = System.currentTimeMillis()/1000;
valueHashMap.put(
Integer.toString((int)timeSinceEpoch)
, people_obj
);
现在我想将哈希图中的所有键放入整数数组列表中。
ArrayList<Integer> intKeys = valueHashMap.keys()...
有什么办法可以做到这一点吗?
I have a hashmap like this
public HashMap <String,People> valueHashMap = new Hashmap();
Here the key to my HashMap is time in seconds as string, ie I am adding value to hashmap like this
long timeSinceEpoch = System.currentTimeMillis()/1000;
valueHashMap.put(
Integer.toString((int)timeSinceEpoch)
, people_obj
);
Now I want to get all keys in the hashmap into an array list of integer.
ArrayList<Integer> intKeys = valueHashMap.keys()...
Is there any way to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有直接的方法将
String
列表转换为Integer
列表:您需要重新定义
valueHashMap
像这样:或者您需要循环:
我建议您使用
Long
作为键:那么就不会转换为
int
(您可以使用上面的 (1) 和Long
来代替)。There is no direct way of converting a list of
String
s to a list ofInteger
s:Either you need to redefine your
valueHashMap
like this:Or you need to loop:
I would advice you however to use the
Long
as key instead:then there would be no casting to
int
(and you can use (1) above withLong
instead).您无法将一种类型的列表转换为另一种类型的列表,因此您必须迭代键并解析每个键。
You can't cast a List of one type to a List of another type, so you have to iterate through the keys and parse each one.
你确实有类型问题。为什么要将长整型改为字符串以将它们存储在映射中。为什么不简单地使用 Long,它需要更少的内存并且更具描述性。那为什么要使用 Integer.toString 将 long 转换为 String 呢?通过将 long 转换为 int,您可能会面临丢失信息的风险。代码可能如下所示:
You really have type problems. Why do you change the longs into Strings to store them in a map. Why not simply use Long, which needs less memory and is more descriptive. Then why use Integer.toString to transform a long into a String? By casting your long to an int, you risk loosing information by. Here's how the code should probably look like:
您可以使用 org.apache.commons.collections.Transformer 类来实现此目的,如下所示。
You can use
org.apache.commons.collections.Transformer
class for that as follows.