gpt4 book ai didi

来自 .csv 文件的 Java 工资总和

转载 作者:行者123 更新时间:2023-12-01 14:32:38 26 4
gpt4 key购买 nike

我正在尝试从 .csv 文件中总结每种工作的薪水,现在我的输出只显示每个人的收入。我需要总结这笔收入,但我不知道如何编写总结每项工作薪水的方法。您知道如何更改我的代码以获得耳环总和吗?

package src;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Path path = Path.of("sample.csv");
try (Stream<String> lines = Files.lines(path);) {
lines.filter(line -> line.startsWith(" "))
.map(line -> LineToPerson(line))
.forEach(System.out::println);
}
catch (IOException e) {
e.printStackTrace();
}
}
private static Person LineToPerson(String line) {
String[] elements = line.split(";");
String id = elements[0];
String name = elements[1];
String surname = elements[2];
String job = elements[3];
Double salary = Double.valueOf(elements[4].replaceAll("\"", "").replaceAll(" ", "").replaceAll(",", "."));
Person p = new Person(id, name, surname, job, salary);
return p;
}
}

--------------------人类------------------------ ----------

package src;

public class Person {

private String id;
private String name;
private String surname;
private String job;
private double salary;

public Person() {

}
public Person(String id, String name, String surname, String job, double salary) {
this.id = id.replaceAll("\"", "").replaceAll(" ", "");
this.name = name.replaceAll("\"", "").replaceAll(" ", "");
this.surname = surname.replaceAll("\"", "").replaceAll(" ", "");
this.job = job.replaceAll("\"", "").replaceAll(" ", "");
this.salary = salary;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getJob() {
return job;
}
public double getSalary() {
return salary;
}
public String toString() {
if (job.equals("Teacher")) {
return "Teacher salary = " + salary;
} else if (job.equals("Janitor")) {
return "Janitor salary = " + salary;
} else return "";
}
}

最佳答案

您需要按照job分组,如下所示:

lines.filter(line -> line.startsWith(" "))
.map(line -> LineToPerson(line))
.collect(Collectors.groupingBy(person -> person.getJob(),
Collectors.summingDouble(person -> person.getSalary())))
.forEach((job,sumSalary) -> System.out.println(job + "\t" + sumSalary));

替换

try (Stream<String> lines = Files.lines(path);) {
lines.filter(line -> line.startsWith(" "))
.map(line -> LineToPerson(line))
.forEach(System.out::println);
}

try (Stream<String> lines = Files.lines(path);) {
lines.filter(line -> line.startsWith(" "))
.map(line -> LineToPerson(line))
.collect(Collectors.groupingBy(person -> person.getJob(),
Collectors.summingDouble(person -> person.getSalary())))
.forEach((job,sumSalary) -> System.out.println(job + "\t" + sumSalary));
}

关于来自 .csv 文件的 Java 工资总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61165676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com