Menu
Coddy logo textTech

Recap - HashMap Operations

Part of the Logic & Flow section of Coddy's Java journey — lesson 21 of 59.

challenge icon

Challenge

Easy

Create a method named <strong>processHashMap</strong> that takes one argument:

  1. A HashMap named <strong>products</strong> where:
    • Keys represent product names (String).
    • Values represent prices (Double).

Operations to Perform

  1. Find the product with the highest price.
    • If multiple products have the same highest price, return any one of them.
    • If the HashMap is empty, return an empty string ("").
  2. Filter products that have a price greater than <strong>50.00</strong> and store them in a new HashMap.
  3. Calculate the average price of all products.
    • If the HashMap is empty, the average should be 0.0.

Return Format

The method should return a new HashMap with the following key-value pairs:

KeyValue
"Highest"The name of the product with the highest price (String).
"Filtered"A HashMap (HashMap<String, Double>) containing only products with prices greater than 50.00.
"Average"The average price of all products (Double).

Try it yourself

import java.util.LinkedHashMap;
import java.util.HashMap;
import java.util.stream.Collectors;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

public class Main {
    public static HashMap<String, Object> processHashMap(HashMap<String, Double> products) {
        // Write your code here
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String productsString = scanner.nextLine();

        // Convert JSON string to HashMap
        Type mapType = new TypeToken<HashMap<String, Double>>(){}.getType();
        HashMap<String, Double> products = new Gson().fromJson(productsString, mapType);

        HashMap<String, Object> result = processHashMap(products);

        // Sort the Filtered map to ensure consistent output
        Map<String, Double> filteredMap = (Map<String, Double>) result.get("Filtered");
        if (filteredMap != null && !filteredMap.isEmpty()) {
            Map<String, Double> sortedFiltered = filteredMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    Map.Entry::getValue,
                    (a, b) -> b,
                    LinkedHashMap::new
                ));
            result.put("Filtered", sortedFiltered);
        }
        
        System.out.println(result);
    }
}

All lessons in Logic & Flow