Teguh Teguh - 5 months ago 10
Java Question

Count amount by grouping list in java

i need to count total doctor transaction using an attribute id, and then total amount payment doctor using an attribute id from list.
how to resolve it? i'm stuck to count it.
please to tell

this is my code:

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;

}
}

Answer

Change the code for:

    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);
    }
Comments