Printout of results in 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 get the answer, but the result is not in the original order, it is shuffled. How can I output lines in the original order?

+3
source share
4 answers

HashMap does not guarantee insertion order. Maybe try LinkedHashMap

+4
source

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

0
source

davin, LinkedHashMap.

You can also 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).");
}
0
source

All you have to do is use a different map implementation (according to other comments). You can change one line to do what you need.

from

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

to

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

Source: https://habr.com/ru/post/1785561/


All Articles