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();
}
}