Sobes.tech
Middle+

Calculate the difference between the largest and smallest DELIVERY orders for each currency. Return the result for each currency, sorted in ascending order of the difference. /** * Returns a map of {currency (sorted by difference) – difference between the largest and smallest DELIVERY order for that currency}. * If there is only one order for a currency, the difference is 0. * Example input: * [ * Order(DELIVERY, "EUR", 2000), * Order(DELIVERY, "USD", 15), * Order(DELIVERY, "RUB", 200), * Order (PICKUP, "RUB", 1250), * Order (DELIVERY, "USD", 35), * Order (PICKUP, "USD", 55), * Order (DELIVERY, "RUB", 100) * ] * * Expected output: * ["EUR" -> 0.0, "USD" -> 20.0, "RUB" -> 100.0] * */ Map<String, Double> getMaxMinusMinDeliveryMapByCurrency(List<OrderData> orderDataList) { }

sobes.tech AI

Answer from AI

Below is an implementation of a Java method that, for a list of orders of type DELIVERY, calculates the difference between the maximum and minimum order value for each currency, and then returns the result as a sorted map by ascending difference:

Map<String, Double> getMaxMinusMinDeliveryMapByCurrency(List<OrderData> orderDataList) {
    Map<String, MinMax> statsByCurrency = new HashMap<>();

    for (OrderData order : orderDataList) {
        if (order == null || order.getType() != Type.DELIVERY) {
            continue;
        }

        String currency = order.getCurrency();
        long amount = order.getAmount();

        statsByCurrency.compute(currency, (key, current) -> {
            if (current == null) {
                return new MinMax(amount);
            } else {
                current.update(amount);
                return current;
            }
        });
    }

    // Convert to list for sorting
    List<Map.Entry<String, Double>> diffList = statsByCurrency.entrySet().stream()
        .map(e -> Map.entry(e.getKey(), e.getValue().diff()))
        .sorted(Comparator.comparingDouble(Map.Entry::getValue))
        .toList();

    // Create a LinkedHashMap to preserve order
    Map<String, Double> result = new LinkedHashMap<>();
    for (Map.Entry<String, Double> entry : diffList) {
        result.put(entry.getKey(), entry.getValue());
    }

    return result;
}

This code:

  • Filters orders by type DELIVERY.
  • Stores the minimum and maximum order value for each currency.
  • Calculates the difference max - min.
  • Sorts currencies by ascending difference.
  • Returns a sorted map with currencies and their corresponding differences.

If there is only one order per currency, the difference will be 0, which meets the condition.