# 如何在forEach中对数字求和

go评论105阅读模式

How to sum number in forEach

# 问题

__label__ความสะอาด，2

__label__สัตว์，1

__label__เผาในที่โล่ง，1

``````public static void main(String[] args) throws Exception {
System.out.print("输入词：");
Scanner ob = new Scanner(System.in);
String input = ob.next();
String str1 = "";
Hashtable<String, Integer> db = new Hashtable<String, Integer>();
while ((str1 = br.readLine()) != null) {
String[] line = str1.split(" ");
String label = line[0];
for (int i = 1; i < line.length; i++) {
if (line[i].equals(input)) {
if (db.containsKey(label)) {
int v = db.get(label);
v = v + 1;
db.put(label, v);
} else {
db.put(label, 1);
}
}
}
}

db.forEach((k, v) -> System.out.println(k + ", " + v));
System.out.print("总和：");
System.out.println("");
}
``````

If I want to count v for sum in last line of code, What should I do. Sorry for bad english.

This is example output that I want.

Input word : เหม็น

__label__ความสะอาด, 2

__label__สัตว์, 1

__label__เผาในที่โล่ง, 1

Sum : 4

``````public static void main(String[] args) throws Exception {
System.out.print(&quot;Input word : &quot;);
Scanner ob = new Scanner(System.in);
String input = ob.next();
String str1 = &quot;&quot;;
Hashtable&lt;String, Integer&gt; db = new Hashtable&lt;String, Integer&gt;();
while ((str1 = br.readLine()) != null) {

String[] line = str1.split(&quot; &quot;);
String label = line[0];
for (int i = 1; i &lt; line.length; i++) {
if (line[i].equals(input)) {
if (db.containsKey(label)) {
int v = db.get(label);
v = v + 1;
db.put(label, v);
} else {
db.put(label, 1);
}
}
}
}

db.forEach( (k, v) -&gt; System.out.println( k + &quot;, &quot; + v) );
System.out.print(&quot;Sum : &quot;);
System.out.println(&quot;&quot;);
}
``````

# 答案1

``````int sum = db.values().stream().mapToInt(Integer::parseInt).sum();
``````

If you want to sum all the values of the `map`, you can use

``````int sum = db.values().stream().mapToInt(Integer::parseInt).sum();
``````

• 本文由 发表于 2020年7月30日 19:58:59
• 转载请务必保留本文链接：https://go.coder-hub.com/63172685.html
• java

go 55

go 56

go 50

go 48