Frequency count of string occured using collections | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Frequency count of string occured using collections

Frequency count of string occured. Can u say any alternative code for following. https://code.sololearn.com/cmo5wCA8Tgfe/?ref=app How to write it through collections!

21st Jun 2020, 5:42 AM
Haritha Vuppula
Haritha Vuppula - avatar
5 Answers
0
I'd suggest you use a HashTable. // Creation Hashtable<String, Integer> counts = new Hashtable<String, Integer>(); // Inserting the first element if it doesn't exist, updating otherwise. // Please replace "<user input>" to make this work. if (!counts.containsKey(<user input>)) counts.put(<user input>, 0); else counts.put(<user input>, counts.get(<user input>) + 1); // Results time! Enumeration keys = counts.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); Integer value = counts.get(key); System.out.println(key + " -> " + value.toString()); } Reference: https://www.geeksforgeeks.org/hashtable-in-java/
21st Jun 2020, 6:39 AM
Felipe BF
0
Felipe BF can u send me whole code plz. i tried to get but it is not working https://code.sololearn.com/cDP95drxWjE1/?ref=app
21st Jun 2020, 10:29 AM
Haritha Vuppula
Haritha Vuppula - avatar
0
Haritha Vuppula There were quite a few errors in your program. Please study them by comparing your version against this one. I forgot "nextElement" returns an Object. https://code.sololearn.com/c7rBGP8mCS3G/?ref=app
21st Jun 2020, 10:52 AM
Felipe BF
21st Jun 2020, 1:11 PM
Haritha Vuppula
Haritha Vuppula - avatar
0
Haritha Vuppula 1. "nextElement" returns an Object. In order to get the String we need, we've got to cast the result to String. I took advantage of the fact "toString" returns a String to make the cast. You can do that when getting the next element, as you pointed out. 2. As a Hashtable accepts Objects as keys and values, I used "Integer" for the values part to avoid an error later in the code if I'd stuck to using the primitive data type "int". An "Integer" is like an "int", but made as a class to use it where an Object is expected. Reference for how Java treats primitives and their equivalent classes: https://stackoverflow.com/a/22471048
21st Jun 2020, 5:14 PM
Felipe BF