gpt4 book ai didi

java - java中通过分组列表来统计数量

转载 作者:行者123 更新时间:2023-12-02 03:34:08 27 4
gpt4 key购买 nike

我需要使用属性 ID 计算医生交易总额,然后使用列表中的属性 ID 计算医生支付总额。怎么解决呢?我忍不住要数它。请告诉

这是我的代码:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SandboxList {
public static void main(String[] args) {

List<Doctor> doctors = new ArrayList<Doctor>();
doctors.add(new Doctor("1726", "John", 10000.00));
doctors.add(new Doctor("4321", "Max", 20000.00));
doctors.add(new Doctor("1726", "John", 40000.00));
doctors.add(new Doctor("4321", "Max", 2000.00));
doctors.add(new Doctor("7765", "Sam", 50000.00));
doctors.add(new Doctor("4321", "Max", 6000.00));

/* I want Output should be Like below
ID : 1726 Name : John Total_payment : 50000.00 total_transaction : 2
ID : 4321 Name : Max Total_payment : 28000.00 total_transaction : 3
ID : 7765 Name : Sam Total_payment : 50000.00 total_transaction : 1

*/

Map<String, List<Doctor>> groupedDoctors = new HashMap<String, List<Doctor>>();
for (Doctor doctor: doctors) {
String key = doctor.doctor_id;
if (groupedDoctors.get(key) == null) {
groupedDoctors.put(key, new ArrayList<Doctor>());
}
groupedDoctors.get(key).add(doctor);
}

Set<String> groupedDoctorsKeySet = groupedDoctors.keySet();
for (String doctorId: groupedDoctorsKeySet) {
List<Doctor> dctrs = groupedDoctors.get(doctorId);
for (Doctor doctor : dctrs) {
System.out.println("ID : "+doctor.doctor_id+"\t"+"Name : "+doctor.doctor_name+"\t"+"total_Payment : "+doctor.doctor_payment);
}
}


}
}

class Doctor {

String doctor_id;
String doctor_name;
Double doctor_payment;

Doctor(String doctor_id, String doctor_name, Double doctor_payment) {

this.doctor_id = doctor_id;
this.doctor_name = doctor_name;
this.doctor_payment = doctor_payment;

}
}

最佳答案

更改代码:

    for (String doctorId : groupedDoctorsKeySet) {
List<Doctor> dctrs = groupedDoctors.get(doctorId);

Double total_payment = 0d;
String doctor_name = null;
for (Doctor doctor : dctrs) {
if (doctor_name == null) {
doctor_name = doctor.doctor_name;
}
total_payment += doctor.doctor_payment;
}
Doctor doctor = new Doctor(doctorId, doctor_name, total_payment);
System.out.println("ID : " + doctor.doctor_id + "\t" + "Name : " + doctor.doctor_name + "\ttotal_Payment : " + doctor.doctor_payment);
}

关于java - java中通过分组列表来统计数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37648758/

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