I have a program that count occurrences of words in given array. It keeps words and its quantity. For example, in given array:
String array[] = {"cat", "dog", "cat"};
I have 2 cats, and 1 dog. Making it with HashMap is quite simple:
HashMap<String, Integer> map = new HashMap<>();
for (int i = 0; i < wordarray.length; i++) {
String word = wordarray[i].toLowerCase();
if (map.containsKey(word)) {
map.put(word, map.get(word) + 1);
} else {
map.put(word, 1);
}
}
Then I just need to print it out:
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
But is there any way to make it without HashMap only using arrays of objects?
Create a custom class to hold your string and int values, and then use an array to hold them. In pseudo-code:
class Myclass
public int myInt;
public string MyString;
//Constructor omited..
//Somewhere else..
MyClass[] my = new Myclass[2];
my[0] = new MyClass("string", 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With