How to convert HashMap keys from String to int in java

Total Post:28

 1433  View(s)
Rate this:

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



Enumeration<?> e = prop.propertyNames();

    while (e.hasMoreElements()) {

           key = (String) e.nextElement();


           hashMap.put(key, intValue);

  1. Post:47

    Re: How to convert HashMap keys from String to int in java

    As 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 {
        private final int first;
        private final int second;
        public IntPair(int first, 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;
        public int getFirst() {
            return first;
        public int getSecond() {
            return second;

      Modified On Apr-09-2018 01:09:36 AM