[英]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. 我需要一些帮助,我正在自己学习如何使用Java处理地图,今天我试图通过键从Hashmap中减去值,但现在我陷入了困境。
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
You will have to parse those strings into Integer first. 您将必须首先将这些字符串解析为Integer。 This is because you are storing values as String
on which arithmetic operations cannot be performed. 这是因为您将值存储为不能在其上执行算术运算的String
。
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)
You will need to first parse the string into integer and then substract it. 您将需要首先将字符串解析为整数,然后将其减去。
It goes like :- 它像:-
int result = Integer.parseInt(map.get(1)) - Integer.parseInt(map.get(2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.