Recap - HashMap Operations
Part of the Logic & Flow section of Coddy's Java journey — lesson 21 of 59.
Challenge
EasyCreate a method named <strong>processHashMap</strong> that takes one argument:
- A HashMap named
<strong>products</strong>where:- Keys represent product names (
String). - Values represent prices (
Double).
- Keys represent product names (
Operations to Perform
- 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 (
"").
- Filter products that have a price greater than
<strong>50.00</strong>and store them in a new HashMap. - Calculate the average price of all products.
- If the HashMap is empty, the average should be
0.0.
- If the HashMap is empty, the average should be
Return Format
The method should return a new HashMap with the following key-value pairs:
| Key | Value |
|---|---|
"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
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap3HashMap Part 2
HashMap MethodsIterate with keySet()Iterate with entrySet()Nested HashMapRecap - Manage WarehouseRecap - HashMap Operations6Advanced Control Flow
Label StatementsSwitch ExpressionPattern MatchingGuard ClausesRecap - Control Flow