I'm new to java and I'm working on a question where I need to output the elements from a HashMap
in the order of the input. I understood that HashMap
cannot do it and LinkedHashMap
was specifically designed to maintain this order. I've implemented the LinkedHashMap
in my problem but the output was not following the input sequence. Kindly help me on that. Please find my question and the code below.
The user enters the number of names n
and the names of the persons (the names are added into a map with name being the key
and the team number he/she belongs to as value
). I should print the respective values
for the names the user enters.
Input: 4
Aurora
Dumbo
Ariel
Bambi
Output: It should be [1,3,1,2]
- the output from the list
But the output I get from the below program is [1,1,2,3]
I've tried to figure out what was my mistake but in vain. Kindly help on this. Thanks.
import java.io.*;
import java.util.*;
public class DonaldPostman {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
Map<String,Integer> m = new LinkedHashMap<String,Integer>();
List<Integer> l = new ArrayList<Integer>();
m.put("Aurora", 1);
m.put("Ariel", 1);
m.put("Alice", 1);
m.put("Phil", 1);
m.put("Peter", 1);
m.put("Olaf", 1);
m.put("Phoebus", 1);
m.put("Ralph", 1);
m.put("Robin", 1);
m.put("Bambi", 2);
m.put("Belle", 2);
m.put("Bolt", 2);
m.put("Mulan", 2);
m.put("Mowgli", 2);
m.put("Mickey", 2);
m.put("Silver", 2);
m.put("Simba", 2);
m.put("Stitch", 2);
m.put("Dumbo", 3);
m.put("Genie", 3);
m.put("Jiminy", 3);
m.put("Kuzko", 3);
m.put("Kida", 3);
m.put("Kenai", 3);
m.put("Tarzan", 3);
m.put("Tiana", 3);
m.put("Winnie", 3);
int n = in.nextInt();
String[] arr = new String[n];
for(int i=0;i<n;i++) {
arr[i] = in.next();
}
Set ms = (Set) m.entrySet();
Iterator it = ms.iterator();
while (it.hasNext()) {
Map.Entry mapEntry = (Map.Entry) it.next();
String key = (String) mapEntry.getKey();
Integer value = (Integer) mapEntry.getValue();
for(int i=0;i<arr.length;i++) {
if(arr[i].equals(key)) {
l.add(value);
}
}
}
System.out.println(l);
}
}