Enables map to print fruits not in any order, but from lowest to most expensive… here is a solution to the problem.
Enables map to print fruits not in any order, but from lowest to most expensive
I’m trying to create a class to represent a fruit store and want to output the available fruits sorted by price from lowest to most expensive. But even if I add the price to my FruitPricesMap in order from cheapest to most expensive, does it always print fruits in the same arbitrary order? How can I get it not to do this?
****FruitStore.java****
import java.util.*;
public class FruitStore {
private Map<String, Double> fruitPricesMap;
public FruitStore() {
fruitPricesMap = new HashMap<>();
}
public boolean addOrUpdateFruit(String fruitName, double fruitPrice) {
fruitPricesMap.put(fruitName, fruitPrice);
return true;
}
public void printAvaliableFruit() {
System.out.println("Avaliable Fruit:");
for (String key : fruitPricesMap.keySet()) {
System.out.printf("%-15s %.2f", key, fruitPricesMap.get(key));
System.out.println();
}
}
}
****FruitStoreApp.java****
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.printAvaliableFruit();
}
}
Current output
Avaliable Fruit:
Apple 2.00
Cherries 3.00
Banana 1.00
The desired output (lowest to highest) :**
**
Avaliable Fruit:
Banana 1.00
Apple 2.00
Cherries 3.00
Solution
You should use TreeMap and specify the order you want in the custom comparator.