HOW TO CONVERT HASHMAP KEYS FROM STRING TO INT IN JAVA

Tom Cruser

Total Post:28

Points:196
Posted by  Tom Cruser
Java 
 1043  View(s)
Ratings:
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<>();

 

prop.load(input);

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

    while (e.hasMoreElements()) {

           key = (String) e.nextElement();

           intValue=Integer.parseInt(prop.getProperty(key));

           hashMap.put(key, intValue);

  1. Pooja Malohtra

    Post:47

    Points:331
    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;

        }

     

        @Override

        public int hashCode() {

            int hash = 3;

            hash = 89 * hash + this.first;

            hash = 89 * hash + this.second;

            return hash;

        }

     

        @Override

        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;

        }

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!