InterviewVault
Welcome back, Sujit Kumar Mishra
Admin
SK Mishra
Revision Mode
Document technical questions and best-practice answers.
Write a Java program to find the Employee who contributed the maximum transaction amount in the last 30 days.
Below is a sample Java program that accomplishes this task. The program assumes you have a list of Transaction objects, each containing an employee ID, transaction amount, and transaction date. It finds the employee whose total transaction amount in the last 30 days is the highest.
import java.time.LocalDate;
import java.util.*;
class Transaction {
String employeeId;
double amount;
LocalDate date;
public Transaction(String employeeId, double amount,
LocalDate date) {
this.employeeId = employeeId;
this.amount = amount;
this.date = date;
}
}
public class MaxTransactionEmployee {
public static void main(String[] args) {
// Sample transactions
List<Transaction> transactions = Arrays.asList(
new Transaction("E001", 500, LocalDate.now().minusDays(2)),
new Transaction("E002", 700, LocalDate.now().minusDays(5)),
new Transaction("E001", 300, LocalDate.now().minusDays(10)),
new Transaction("E003", 1200, LocalDate.now().minusDays(20)),
new Transaction("E002", 400, LocalDate.now().minusDays(25)),
new Transaction("E003", 600, LocalDate.now().minusDays(35))
// Outside 30 days
);
// Find employee with maximum transaction amount in last 30 days
String maxEmployee = findMaxEmployee(transactions);
System.out.println("Employee with maximum transaction
amount in last 30 days: " + maxEmployee);
}
public static String findMaxEmployee
(List<Transaction> transactions) {
LocalDate today = LocalDate.now();
LocalDate thresholdDate = today.minusDays(30);
// Map to store total amount per employee
Map<String, Double> employeeTotals = new HashMap<>();
for (Transaction tx : transactions) {
if (!tx.date.isBefore(thresholdDate)) {
employeeTotals.put(
tx.employeeId,
employeeTotals.getOrDefault(tx.employeeId, 0.0)
+ tx.amount
);
}
}
// Find employee with maximum total
String maxEmployee = null;
double maxAmount = 0.0;
for (Map.Entry<String, Double> entry :
employeeTotals.entrySet()) {
if (entry.getValue() > maxAmount) {
maxAmount = entry.getValue();
maxEmployee = entry.getKey();
}
}
return maxEmployee;
}
}
NOTE: The getOrDefault() method in Java’s HashMap is used to retrieve the value associated with a specified key, or return a default value if the key does not exist in the map.
How It Works
1: Transaction Class: Represents a transaction with employee ID, amount, and date.
2: Main Method: Creates sample transactions and calls the method to find the employee with the highest total in the last 30 days.
3: findMaxEmployee:
- Filters transactions within the last 30 days.
- Sums amounts per employee.
- Finds the employee with the maximum total.