java - Elegant solution for string-counting? -
the problem have example of i've seen often. have series of strings (one string per line, lets say) input, , need return how many times each string has appeared. elegant way solve this, without using trie or other string-specific structure? solution i've used in past has been use hashtable-esque collection of custom-made (string, integer) objects implements comparable keep track of how many times each string has appeared, method seems clunky several reasons:
1) method requires creation of comparable function identical string's.compareto().
2) impression i'm misusing treeset, has been collection of choice. updating counter given string requires checking see if object in set, removing object, updating object, , reinserting it. seems wrong.
is there more clever way solve problem? perhaps there better collections interface use solve problem?
thanks.
one posibility can be:
public class counter { public int count = 1; } public void count(string[] values) { map<string, counter> stringmap = new hashmap<string, counter>(); (string value : values) { counter count = stringmap.get(value); if (count != null) { count.count++; } else { stringmap.put(value, new counter()); } } }
in way still need keep map @ least don't need regenerate entry every time match new string, can access counter class, wrapper of integer , increase value one, optimizing access array
Comments
Post a Comment