Search code examples
javacollectionshashmapsubtraction

Java subtract values in HashMaps by key


I need some help, I'm learning by myself how to deal with maps in Java and today I was trying to get the subtraction of the values from a Hashmap via key but now I am stuck.

These are the map values that I want to subtract (arithmetic subtraction between the values with keys ).

HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(1, "10");
map.put(2, "5");

In the below i want to subtract by key like

 (key1) - (key2) = 5

Solution

  • You will have to parse those strings into Integer first. This is because you are storing values as String on which arithmetic operations cannot be performed.

    Integer.parseInt(map.get(1)) - Integer.parseInt(map.get(2))
    

    Alternative you can store values as integers like this.

    HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
    map.put(1, 10);
    map.put(2, 5);
    

    and perform below

    map.get(1) - map.get(2)