-1

I need my output for this code to be in the order that was entered into the console. Currently, the output is in the order of most occurrences. Not sure how to change it to come return results in order entered. For example I need: Enter Seven Numbers :12 23 44 22 23 22 55 to return Number 12 occurs 1 times Number 23 occurs 2 times Number 44 occurs 1 times Number 22 occurs 2 times Number 55 occurs 1 times

import java.util.*;
import java.util.Map.Entry;
public class CountOccurrences7Integers {
    public static void main(String[] args) {

        System.out.println("Alina's Copy ");

        System.out.print("Enter Seven Numbers :");

        // An array to hold seven elements

        int[] numbers = new int[7];


        // loop reads input up to 7 integers from the console

        Scanner input = new Scanner(System.in);

        for (int i = 0; i < 7; i++) {

        if (input.hasNextInt()) {

        numbers[i] = input.nextInt();

        } 

        }

        //countMap holds the count details of each element

        Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();

        for (int i = 0; i < numbers.length; i++)

        {

        int key = numbers[i];

        if (countMap.containsKey(key))

        {

        int count = countMap.get(key);

        count++;

        countMap.put(key, count);

        } else

        {

        countMap.put(key, 1);

        }

        }

        //Printing the Element and its occurrence in the array

        for(Entry<Integer, Integer> val : countMap.entrySet())

        {

        System.out.println("Number "+val.getKey() + " occurs " + val.getValue() + " times");

        }

          input.close();

        }

}
User 0505
  • 1
  • 5
  • try using a `LinkedHashMap` instead https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html in which order is determined by the insertion order. – Allan Feb 26 '18 at 04:35
  • Possible duplicate of [Java Ordered Map](https://stackoverflow.com/questions/663374/java-ordered-map) – Allan Feb 26 '18 at 04:36

1 Answers1

0

To maintain the insertion order, use a LinkedHashMap instead of a HashMap.

From javadoc (emphasis mine)

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

Thiyagu
  • 17,362
  • 5
  • 42
  • 79