Мне нужно написать приложение, которое принимает строку и возвращает количество уникальных символов в строке. встречается < /p>
На этом этапе мое приложение уже может считать и отображать символы < /p>
Код: Выделить всё
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 charCounter(String[] args) {
LinkedHashMap elements = new LinkedHashMap();
List 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 iterator
= map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry 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();
}
}
< /code>
Результат приложения < /p>
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
< /code>
Теперь мне нужно научить свое приложение к кэшу и проверить входные данные на предмет уже существующего результата. < /p>
Я думаю, что загрузка Cache из Guava поможет мне < /p>
LoadingCache graphs = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.removalListener(MY_LISTENER)
.build(
new CacheLoader() {
@Override
public Graph load(Key key) throws AnyException {
return createExpensiveGraph(key);
}
});
Подробнее здесь: https://stackoverflow.com/questions/704 ... he-results