You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让FruitStore按价格从低到高输出水果而非任意顺序?

解决按价格排序输出水果店水果的问题

Ah, I get it—you're running into a classic HashMap behavior issue here! Let me break down what's happening and how to fix it.

Why Your Current Code Isn't Working

The HashMap you're using doesn't preserve any order—neither the order you insert elements in, nor a sorted order. It uses hash codes to store elements, so the output order will always seem random, no matter how you add your fruits. That's exactly why your output is jumbled even though you added fruits from lowest to highest price.

The most flexible approach is to keep using HashMap for efficient storage, then sort the entries only when you need to print them. This way, you get the best of both worlds: fast insertions/updates, and sorted output whenever you want it.

Here's the modified FruitStore.java with this approach (I also fixed the typo in printAvaliableFruit to printAvailableFruit):

import java.util.*;
public class FruitStore {
    private Map<String, Double> fruitPricesMap;
    public FruitStore() {
        fruitPricesMap = new HashMap<>(); // Keep using HashMap for efficiency
    }
    public boolean addOrUpdateFruit(String fruitName, double fruitPrice) {
        fruitPricesMap.put(fruitName, fruitPrice);
        return true;
    }
    public void printAvailableFruit() {
        System.out.println("Available Fruit:");
        // Convert map entries to a list so we can sort them
        List<Map.Entry<String, Double>> sortedFruits = new ArrayList<>(fruitPricesMap.entrySet());
        
        // Sort by price ascending; if prices are equal, sort by fruit name to avoid ties
        sortedFruits.sort((entry1, entry2) -> {
            int priceComparison = Double.compare(entry1.getValue(), entry2.getValue());
            if (priceComparison == 0) {
                return entry1.getKey().compareTo(entry2.getKey());
            }
            return priceComparison;
        });
        
        // Print the sorted list
        for (Map.Entry<String, Double> fruit : sortedFruits) {
            System.out.printf("%-15s %.2f%n", fruit.getKey(), fruit.getValue());
        }
    }
}

And update FruitStoreApp.java to use the corrected method name:

public class FruitStoreApp {
    public static void main(String[] args) {
        FruitStore fs = new FruitStore();
        fs.addOrUpdateFruit("Banana", 1.00);
        fs.addOrUpdateFruit("Apple", 2.00);
        fs.addOrUpdateFruit("Cherries", 3.00);
        fs.printAvailableFruit(); // Fixed method name
    }
}

Solution 2: Use TreeMap for Sorted Storage

If you want the map itself to maintain sorted order at all times, you can use TreeMap with a custom comparator that sorts by fruit price. However, note that TreeMap sorts based on keys, so we need to adjust the comparator to compare values (prices) instead. Also, if you update a fruit's price, you'll need to remove and re-add the entry to trigger a re-sort.

Modified FruitStore.java with TreeMap:

import java.util.*;
public class FruitStore {
    private Map<String, Double> fruitPricesMap;
    public FruitStore() {
        // Custom comparator: sort by price ascending, then name ascending for ties
        fruitPricesMap = new TreeMap<>((fruit1, fruit2) -> {
            double price1 = fruitPricesMap.get(fruit1);
            double price2 = fruitPricesMap.get(fruit2);
            int priceCompare = Double.compare(price1, price2);
            if (priceCompare == 0) {
                return fruit1.compareTo(fruit2);
            }
            return priceCompare;
        });
    }
    public boolean addOrUpdateFruit(String fruitName, double fruitPrice) {
        // Remove and re-add to ensure TreeMap re-sorts when price changes
        if (fruitPricesMap.containsKey(fruitName)) {
            fruitPricesMap.remove(fruitName);
        }
        fruitPricesMap.put(fruitName, fruitPrice);
        return true;
    }
    public void printAvailableFruit() {
        System.out.println("Available Fruit:");
        for (String key : fruitPricesMap.keySet()) {
            System.out.printf("%-15s %.2f%n", key, fruitPricesMap.get(key));
        }
    }
}

Which Solution Should You Choose?

  • Go with Solution 1 if you mostly need sorted output but want fast insertions/updates. It's more flexible and avoids the overhead of maintaining a sorted structure at all times.
  • Use Solution 2 only if you need the map to stay sorted for other operations besides printing (e.g., iterating in sorted order elsewhere in your code).

With either solution, you'll get your desired output:

Available Fruit:
Banana 1.00
Apple 2.00
Cherries 3.00

内容的提问来源于stack exchange,提问作者David Nichols

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:46:03