I am trying to create a class to represent a Fruit Store, and want to output the available fruit sorted by price, from least to most expensive. However, even though I add prices to my FruitPricesMap in the order of least expensive to most expensive it always prints the fruits in the same arbitrary order? How can I make it not 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
****Desired output (least expensive to most expensive):****
Avaliable Fruit:
Banana 1.00
Apple 2.00
Cherries 3.00