Skip to content
Advertisement

How to iterate through ArrayList values of HashMap?

A question from a total newbie. Sorry.

I have this customersOrders HashMap that takes String as keys and ArrayList<Double> as values. I need to find the total sum of orders for each customer and the maximum total sum in order to find the biggest customer. How do I manage to do that using just nested For loops and HashMap methods? I’m totally stuck on that.

public class Test {

    public static void main(String[] args) {

        HashMap<String, ArrayList<Double>> customersOrders;

        customersOrders = new HashMap<>();
        ArrayList<Double> orders = new ArrayList<>();
        orders.add(55.50);
        orders.add(78.30);
        orders.add(124.75);
        customersOrders.put("John", orders);

        orders = new ArrayList<>();
        orders.add(28.35);
        orders.add(37.40);
        customersOrders.put("Helen", orders);

        orders = new ArrayList<>();
        orders.add(150.10);
        customersOrders.put("Thomas", orders);

        orders = new ArrayList<>();
        orders.add(230.45);
        orders.add(347.20);
        customersOrders.put("Robert", orders);

        orders = new ArrayList<>();
        orders.add(530.25);
        orders.add(325.40);
        orders.add(11550.70);
        orders.add(2480.65);
        customersOrders.put("Jennifer", orders);

        System.out.println(customersOrders);

    }
}

So far I’ve been trying to do something like this but obviously with no success:

double maxOrder = 0;
String customerName = "";

for (ArrayList<Double> orders : customersOrders.values()) {
    for (double orderPrice : orders) {
        if (orderPrice > maxOrder) {
            maxOrder = orderPrice;
        }
    }
}
        
for (String name : customersOrders.keySet()) {
    if (maxOrder.equals(customersOrders.get(name))) {
        customerName = name;
        break;
    }
}

Advertisement

Answer

You could create another HashMap which keeps your sums and then find the maximum of them.

First iterate through all your HashMap keys and find the sums for each customer like this:

HashMap<String, ArrayList<Double>> customerOrders = new HashMap<>();
// Fill your HashMap as you've done above

HashMap<String, Double> customerSums = new HashMap<>(); // The new HashMap that keeps the sums

for (String customerName : customerOrders.keySet()) // Foreach customer
{
    double currentSum = 0;
    for (Double aDouble : customerOrders.get(customerName)) 
    {
        currentSum += aDouble; // Sum the orders
    }
    
    customerSums.put(customerName, currentSum); // Put the sum in your new HashMap
    
}

Now finding the maximum should be very straightforward. Try to do that 😀

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement