I'm learning programming in the language java.
I need to write an application that takes a string and returns the number of unique characters in the string. It is expected that a string with the same character sequence may be passed several times to the method. Since the counting operation can be time-consuming, the method should cache the results, so that when the method is given a string previously encountered
At this stage, my application is already able to count and display characters
public class Main {
public static void main(String[] args) {
String[] testArray = new String[]{"Java", "is", "the", "best", "programming",
"language", "in", "the", "world!"};
CharCounter charCounter = new CharCounter();
Print print = new Print();
print.printArgs(testArray);
print.print(charCounter.charCounter(testArray));
}
}
/**
* CharCounter should takes a string and returns the number of unique
* characters in the string.
*/
public class CharCounter {
public LinkedHashMap<Character, Integer> charCounter(String[] args) {
LinkedHashMap<Character, Integer> elements = new LinkedHashMap();
List<Character> chars = new ArrayList();
for (char c : stringToCharArray(args)) {
chars.add(c);
}
for (Character element : chars) {
if (elements.containsKey(element)) {
elements.put(element, elements.get(element) + 1);
} else {
elements.put(element, 1);
}
}
return elements;
}
/**
* stringToCharArray method - convert string array to character array *
*/
private char[] stringToCharArray(String[] args) {
String s = "";
for (String agr : args) {
if (s == "") {
s = agr;
} else {
s = s + " " + agr;
}
}
return s.toCharArray();
}
}
/**
* The Print class is intended to output the result to the console
*/
public class Print {
public void print(Map map) {
Iterator<Map.Entry<Character, Integer>> iterator
= map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Character, Integer> charCounterEntry = iterator.next();
System.out.printf("\"%c\" - %d\n", charCounterEntry.getKey(),
charCounterEntry.getValue());
}
}
public void printArgs(String[] args) {
for (String arg : args) {
System.out.printf("%s ", arg);
}
System.out.println();
}
}
The result of the application
Java is the best programming language in the world!
"J" - 1
"a" - 5
"v" - 1
" " - 8
"i" - 3
"s" - 2
"t" - 3
"h" - 2
"e" - 4
"b" - 1
"p" - 1
"r" - 3
"o" - 2
"g" - 4
"m" - 2
"n" - 3
"l" - 2
"u" - 1
"w" - 1
"d" - 1
"!" - 1
Now I need to teach my application to cache and check the input data for an already existing result.
I think LoadingCache from Guava will help me
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.removalListener(MY_LISTENER)
.build(
new CacheLoader<Key, Graph>() {
@Override
public Graph load(Key key) throws AnyException {
return createExpensiveGraph(key);
}
});
Please help me pair my app with LoadingCache.
To all who will respond, thanks a lot!