Home > DeveloperSection > Forums > How to convert HashMap keys from String to int in java
Tom Cruser
Tom Cruser

Total Post:28

Points:196
Posted on    February-04-2015 10:19 PM

 OOPS Java 
Ratings:


 1 Reply(s)
 649  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<>();

 

prop.load(input);

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

    while (e.hasMoreElements()) {

           key = (String) e.nextElement();

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

           hashMap.put(key, intValue);



Pooja Malohtra
Pooja Malohtra

Total Post:47

Points:331
Posted on    February-04-2015 10:42 PM

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;

    }

}


Don't want to miss updates? Please click the below button!

Follow MindStick