3

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
  • 1
    Possible duplicate of [Sorting HashMap by values](https://stackoverflow.com/questions/8119366/sorting-hashmap-by-values) – karan Jan 19 '19 at 06:52
  • 1
    Possible duplicate of [java HashMap sorting . How to sort it?](https://stackoverflow.com/questions/12229577/java-hashmap-sorting-string-integer-how-to-sort-it) – Kartik Jan 19 '19 at 07:00

2 Answers2

2

You should use a TreeMap and specify the order you would like in a custom comparator.

YetAnotherBot
  • 1,937
  • 2
  • 25
  • 32
1

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<>();
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40