-1

We have recently learned how to use HashMaps and the only problem I am getting is how to put them in the order I want. I want my quarter sales to go from 1-4, but right now it is printing Quarter sales 2, 3, 4, 1.

Map<String, String> quarterSalesMap = new HashMap<>();
        quarterSalesMap.put("Quarter 1 sales", "$5,886.61");
        quarterSalesMap.put("Quarter 2 sales", "$8,261.80");
        quarterSalesMap.put("Quarter 3 sales", "$8,435.86");
        quarterSalesMap.put("Quarter 4 sales", "$8,108.74");
            for(Map.Entry sales : quarterSalesMap.entrySet()){
                System.out.println(sales.getKey() + ": " + sales.getValue()); 
Avery O
  • 63
  • 5
  • 1
    Why use a map if you want to guarantee order? In any case, there's `TreeMap`, `LinkedHashMap`, and so on. – Dave Newton Jan 23 '19 at 17:13
  • Do you want the map to respect insertion order, or do you want it to respect a custom or natural order, irrespective of the order you put entries into it? – fps Jan 23 '19 at 17:16

1 Answers1

2

The HashMap is a unordered and unsorted Map. Use LinkedHashMap for a map that uses insertion order or a TreeMap to sort Strings by their natural order.

Dorian Gray
  • 2,913
  • 1
  • 9
  • 25