i wrote a small java program that uses Hashmap. The program prompts to enter 3 employee names with its salary. After entering the 3 employees with salaries, I just want to simply output the map key and values in the console. However, I have observed that the output is not ordered the same way as I input.
Sample input
Enter employee name 1:> Dara
Enter salary for Dara:> 200
Enter employee name 2:> Logan
Enter salary for Logan:> 300
Enter employee name 3:> Agnes
Enter salary for Logan:> 300
Output looks like this:
Agnes > 300.0
Logan > 300.0
Dara > 200.0
Observe that Dara is now placed at the bottom and Agnes is on top. It should be the other way around as how I input it. Please see my code below.
public class Maps {
static String name = "";
static double salary = 0;
static Scanner sc = new Scanner(System.in);
static Map<String, Double> m = new HashMap<String, Double>();
public static void main(String[] args) {
Maps ms = new Maps();
int count = 1;
while(count <= 3){
System.out.println("Enter employee " + count);
name = sc.next();
System.out.println("------------------");
System.out.println("Enter salary for " + name);
salary = sc.nextDouble();
System.out.println("\n");
m.put(name, salary);
count += 1;
}
ms.displayMap();
}
public void displayMap(){
System.out.println("========================");
**I think the issue lies in here**
for(Entry<String, Double> employee : m.entrySet()){
String key = employee.getKey();
Double value = employee.getValue();
System.out.println(key + " \t " + value);
}
}
}