如何在forEach中对数字求和

huangapple go评论107阅读模式
英文:

How to sum number in forEach

问题

如果我想要计算最后一行代码中的变量v的总和,我应该怎么做。对不起,我的英语不好。

这是我想要的示例输出。

输入词:เหม็น

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

__label__สัตว์,1

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

总和:4

public static void main(String[] args) throws Exception {
    System.out.print("输入词:");
    BufferedReader br = new BufferedReader(new FileReader("d:\\input2.txt"));
    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;);
    BufferedReader br = new BufferedReader(new FileReader(&quot;d:\\input2.txt&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

得分: 1

如果您想要对map中的所有值求和,您可以使用

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();

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

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定