Sam
Sam

Reputation: 29

Printing the results in the original order

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?

Upvotes: 3

Views: 199

Answers (4)

Shane
Shane

Reputation: 1285

All you need to do is use a different Map implementation (as per other comments). You can change a single line to do what you need.

from

Map<String, Integer> map = new HashMap<String, Integer>();

to

Map<String, Integer> map = new LinkedHashMap<String, Integer>();

Upvotes: 0

jzd
jzd

Reputation: 23629

Like davin mentioned use a LinkedHashMap.

Also you can use the "foreach" loop in Java and replace:

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).");
}

With

for(String key: map.keySet()) {
    int occurrence = map.get(key);
    System.out.println(key + " occur " + occurrence + " time(s).");
}

Upvotes: 0

Ankur
Ankur

Reputation: 788

Using java.util.TreeMap, it implements SortedMap interface, you can provide the comparator. Use firstKey() to get smallest key, use it to getValue i.e count and remove it from the map and repeat the call from firstKey()

Upvotes: 0

davin
davin

Reputation: 45545

HashMap doesn't guarantee insertion order. Maybe try LinkedHashMap

Upvotes: 4

Related Questions