java Get hashmap keys as integer array
Solution 1
There is no direct way of converting a list of String
s to a list of Integer
s:
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());
Or you need to loop:
ArrayList<Integer> intKeys = new ArraList<Integer>(); for (String stringKey : valueHashMap.keySet()) intKeys.add(Integer.parseInt(stringKey);
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 withLong
instead).
Solution 2
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));
}
Krishnabhadra
After having dates with C, C++, 8051, AVR, Linux, QT now concentrating on mobile application development(iOS and Android). Still plays with C now and then, can't live without. Now making swift progress with Swift. A post graduate in Electronics, switched career to become a application software developer. Now a proud owner of iOS gold badge :) SOreadytohelp
Updated on July 20, 2022Comments
-
Krishnabhadra almost 2 years
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?