开发者

java Get hashmap keys as integer array

I have a hashmap like this

public HashMap <String,People> valueHashMap  = new Hashmap();

Here the key to my HashMap i开发者_运维知识库s 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?


There is no direct way of converting a list of Strings to a list of Integers:

  1. Either you need to redefine your valueHashMap like this:

    public HashMap<Integer, People> valueHashMap  = new HashMap<Integer, People>();
    
    ....
    
    ArrayList<Integer> intKeys = new ArrayList<Integer>(valueHashMap.keySet());
    
  2. Or you need to loop:

    ArrayList<Integer> intKeys = new ArraList<Integer>();
    
    for (String stringKey : valueHashMap.keySet())
         intKeys.add(Integer.parseInt(stringKey);
    
  3. I would advice you however to use the Long as key instead:

    public HashMap<Long, People> valueHashMap  = new HashMap<Long, People>();
    

    then there would be no casting to int (and you can use (1) above with Long 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.

for(String k : valueHashMap.keySet()) {
    intKeys.add(Integer.valueOf(k));
}


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:

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());


You can use org.apache.commons.collections.Transformer class for that as follows.

List<Integer> intKeys  = (List<Integer>)CollectionUtils.collect(valueHashMap.keySet(), new Transformer() {
                                    @Override
                                    public Object transform(Object key) {
                                        return Integer.valueOf(key);
                                    }
                                }, new ArrayList<Integer>());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜