Convert Hashmap to a single-line array in java

I am working on a class program and have been beating my head for several days. I need to find the number of occurrences in a string. I was able to get the results in HashMap. However, I need to be able to convert it to a single array of strings so that I can assertTrue and test it. Here is what I still have. Any suggestions would be appreciated. Thank.

public static void main(String[] args) 
    {
        String input = "xyz 456 123 123 123 123 123 123 xy 98 98 xy xyz abc abc 456 456 456  98 xy"; //String to be tested
        String[] str = input.split(" "); // String put into an array

        Map<String, Integer> occurrences = new HashMap<String, Integer>();
        Integer oldValue = 0;

        for (String value : str)
        {
            oldValue = occurrences.get(value);
            if (oldValue == null)
            {
                occurrences.put(value, 1); 
            } else
            {
                occurrences.put(value, oldValue + 1);
            }
        }
        occurrences.remove("");

}

Target array of strings:

[xy, 3, 123, 6, abc, 2, 456, 4, xyz, 2, 98, 3]
+4
source share
1 answer

The question is, how can you read key-value pairs from your hash file?

Then, the following example demonstrates some simple indications:

for(String entry : occurrences.keySet()) {
    Integer value = occurrences.get(entry);         
    System.out.println(entry + ":" + value);
}

Conclusion:

xy:3
123:6
abc:2
456:4
xyz:2
98:3

Update:

[, , , ,...], :

ArrayList<String> strings = new ArrayList<>();

for(String entry : occurrences.keySet()) {
    strings.add(entry);
    strings.add(""+occurrences.get(entry));
}

String[] asArray = strings.toArray(new String[strings.size()]);

ArrayList:

String[] asArray = new String[occurrences.size()*2];
int index = 0;

for(String entry : occurrences.keySet()) {
    asArray[index++]=entry;
    asArray[index++]=""+occurrences.get(entry);
}
+3

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


All Articles