Skip to content

Instantly share code, notes, and snippets.

@amirul12
Created November 10, 2024 03:39
Show Gist options
  • Save amirul12/1dbd46f49893f3879feb6d9a4152138d to your computer and use it in GitHub Desktop.
Save amirul12/1dbd46f49893f3879feb6d9a4152138d to your computer and use it in GitHub Desktop.
In Java, a TreeMap is part of the java.util package and implements the NavigableMap interface. It stores key-value pairs in a sorted order based on the keys. A common use case of TreeMap is to store account balances of customers, where the account balance is the key, and the account holder or other information is the value. You can then use this…
import java.util.Map;
import java.util.TreeMap;
public class InterestCalculation {
public static void main(String[] args) {
// Creating a TreeMap to store account balances sorted by balance
TreeMap<Double, String> accountBalances = new TreeMap<>();
// Adding account balances and account holder names
accountBalances.put(5000.00, "John Doe");
accountBalances.put(15000.00, "Jane Smith");
accountBalances.put(3000.00, "Alice Johnson");
accountBalances.put(25000.00, "Bob Brown");
accountBalances.put(12000.00, "Charlie Davis");
// Print header for the interest report
System.out.println("Account Balance Interest Report");
System.out.println("--------------------------------");
// Iterate through the TreeMap and calculate interest on each balance
for (Map.Entry<Double, String> entry : accountBalances.entrySet()) {
Double balance = entry.getKey();
String accountHolder = entry.getValue();
// Calculate interest based on balance
double interestRate = getInterestRate(balance);
double interest = balance * interestRate;
// Print the account holder, balance, interest rate, and interest
System.out.printf("Account Holder: %-15s | Balance: $%-10.2f | Interest: $%-10.2f | Rate: %.2f%%\n",
accountHolder, balance, interest, interestRate * 100);
}
}
// Method to determine interest rate based on balance
public static double getInterestRate(double balance) {
if (balance < 5000) {
return 0.01; // 1% interest for balances below $5000
} else if (balance < 10000) {
return 0.02; // 2% interest for balances between $5000 and $9999
} else if (balance < 20000) {
return 0.03; // 3% interest for balances between $10000 and $19999
} else {
return 0.04; // 4% interest for balances over $20000
}
}
}
@amirul12
Copy link
Author

Key Points:
Sorted by Balance: Since TreeMap stores keys in sorted order, the account balances are displayed in ascending order.
Interest Calculation: The method getInterestRate() determines the interest rate based on the balance, making it easy to adjust interest rules as needed.
Formatting Output: The System.out.printf() function is used to display a nicely formatted report.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment