Make Map not print Fruits in arbitrary order, but in order of least to most expensive

David Nichols :

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
shash678 :

You could use a LinkedHashMap, and make sure to ensure to insert the fruits into the map in the order from least to most expensive since it maintains insertion order, unlike the regular HashMap.

I.e. Change the line:

fruitPricesMap = new HashMap<>();

to this:

fruitPricesMap = new LinkedHashMap<>();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=96229&siteId=1