[英]java Get hashmap keys as integer array
我有这样的哈希映射
public HashMap <String,People> valueHashMap = new Hashmap();
这里我的HashMap的关键是以字符串为单位的秒数,即我正在像这样向hashmap添加值
long timeSinceEpoch = System.currentTimeMillis()/1000;
valueHashMap.put(
Integer.toString((int)timeSinceEpoch)
, people_obj
);
现在我想将hashmap中的所有键都放入整数数组列表中。
ArrayList<Integer> intKeys = valueHashMap.keys()...
有没有办法做到这一点?
没有直接的方法将String
列表转换为Integer
列表:
您需要重新定义valueHashMap
如下所示:
public HashMap<Integer, People> valueHashMap = new HashMap<Integer, People>(); .... ArrayList<Integer> intKeys = new ArrayList<Integer>(valueHashMap.keySet());
或者你需要循环:
ArrayList<Integer> intKeys = new ArraList<Integer>(); for (String stringKey : valueHashMap.keySet()) intKeys.add(Integer.parseInt(stringKey);
我会建议你使用Long
作为密钥 :
public HashMap<Long, People> valueHashMap = new HashMap<Long, People>();
然后就没有铸造int
(你可以使用上述(1)用Long
来代替)。
您不能将一种类型的List转换为另一种类型的List,因此您必须遍历这些键并解析每个类型。
for(String k : valueHashMap.keySet()) {
intKeys.add(Integer.valueOf(k));
}
你真的有类型问题。 为什么要将长片更改为字符串以将其存储在地图中。 为什么不简单地使用Long,它需要更少的内存并且更具描述性。 那么为什么要使用Integer.toString将long转换为String呢? 通过将您的long转换为int,您可能会失去信息。 以下是代码的外观:
private Map<Long, People> valueHashMap = new Hashmap<Long, People>();
long timeSinceEpoch = System.currentTimeMillis()/1000;
valueHashMap.put(timeSinceEpoch, people_obj);
List<Long> longKeys = new ArrayList<Long>(valueHashMap.keySet());
您可以使用org.apache.commons.collections.Transformer
类,如下所示。
List<Integer> intKeys = (List<Integer>)CollectionUtils.collect(valueHashMap.keySet(), new Transformer() {
@Override
public Object transform(Object key) {
return Integer.valueOf(key);
}
}, new ArrayList<Integer>());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.