Printing the results in the original order
Posted
by
Sam
on Stack Overflow
See other posts from Stack Overflow
or by Sam
Published on 2011-01-14T23:36:29Z
Indexed on
2011/01/14
23:53 UTC
Read the original article
Hit count: 134
java
String[] numbers = new String[] {"3", "4", "s", "a", "c", "h", "i", "n", "t", "e", "n", "d", "u", "l", "k"};
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < numbers.length; i++) {
String key = numbers[i];
if (map.containsKey(key)) {
int occurrence = map.get(key);
occurrence++;
map.put(key, occurrence);
} else {
map.put(key, 1);
}// end of if else
}// end of for loop
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
int occurrence = map.get(key);
System.out.println(key + " occur " + occurrence + " time(s).");
}
This program tries to count the number of occurrences of a string. When I execute it I am getting the answer, but the output is not in the original order, it is shuffled. How can I output the strings in the original order?
© Stack Overflow or respective owner