英文:
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("Input word : ");
    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("Sum : ");  
    System.out.println("");
}
答案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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论