Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 247
Krishnabhadra Avatar asked Apr 27 '26 10:04

Krishnabhadra


1 Answers

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).

like image 163
dacwe Avatar answered Apr 29 '26 01:04

dacwe