I have a HashMap and a properties file that holds
key/values. Properties file stores keys/values in this format "4,5=2"
I have built a method that loads properties from the file and it puts the pair
of "keys/value" into a HashMap Array(String, Integer). But my problem
is that I want each element of keys to be stored as an int, in order to use
them as parameters to another method. Keys are stored as String. Any help would
be appreciated. Thank you!
public static HashMap<String, Integer> hashMap = new HashMap<>();
prop.load(input);
Enumeration<?> e = prop.propertyNames();
while (e.hasMoreElements())
{
key = (String)
e.nextElement();
intValue=Integer.parseInt(prop.getProperty(key));
hashMap.put(key,
intValue);
Aryan Kumar
04-Jul-2023Sure. To convert HashMap keys from string to int in Java, you can use the following steps:
Here is an example of how to convert HashMap keys from string to int in Java:
Java
This code will create a HashMap with three entries: "one" -> 1, "two" -> 2, and "three" -> 3. The code will then iterate through the HashMap and convert each key from string to int. Finally, the code will print the HashMap with the converted keys.
The output of the code will be:
Code snippet
Anonymous User
04-Feb-2015As you key seems to be a pair of integers, you need a Pair class to be used as a key. Then just access getFirst() or getSecond() to be used with your other api.
public class IntPair {
public IntPair(int first, int second) {
@Override
@Override
public int getFirst() {
public int getSecond() {private final int first;
private final int second;
this.first = first;
this.second = second;
}
public int hashCode() {
int hash = 3;
hash = 89 * hash + this.first;
hash = 89 * hash + this.second;
return hash;
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final IntPair other = (IntPair) obj;
if (this.first != other.first) {
return false;
}
if (this.second != other.second) {
return false;
}
return true;
}
return first;
}
return second;
}
}