I have a function that takes a description as a String
and returns a shortened version of the description.
The shortening is done by checking if a word matches the key of the HashMap<String,String> map
and replaces the word by its abbreviation defined as the value in the HashMap
. If the word cannot be found it in the HashMap
it will not be replaced (it stays the same). If the value of a word is <remove>
the word will be removed from the new description.
There can be multiple abbreviations for the same word.
Example:
AUTOMATIC GAIN CONTROL --> AGC
CONTROL --> CTRL
In any case the function should always take the abbreviation which takes the most words.
Consider this example mapping:
AUTOMATIC GAIN CONTROL --> AGC
CONTROL --> CTRL
IDENTIFIER --> ID
THE -->
<remove>
The input String
:
The Automatic Gain Control identifier value
will result in the output String
:
AGC ID value
The String
's in the HashMap
are all uppercase and the abbreviation in the output String
should also be uppercase. However, any word that was not found in the HashMap
should stay the same as it was in the input String
.
My function seems to do the task correctly but I'm not sure if it could have been written better and/or more efficiently.
private static HashMap<String,String> map = new HashMap<String, String>();
public static String shortenText(String input){
ArrayList<String> listUpperCase = new ArrayList<String>(Arrays.asList(new String(input).toUpperCase().split(" ")));
ArrayList<String> list = new ArrayList<String>(Arrays.asList(input.split(" ")));
//Remove any words that map to <remove>
for (int i=0;i<list.size();i++){
String value = map.get(listUpperCase.get(i));
if (value!=null){
if(value.equals("<remove>")){
list.remove(i);
listUpperCase.remove(i);
}
}
}
//Replace words by their abbreviation
StringBuilder builder = new StringBuilder();
for (int i=0;i<list.size();i++){
StringBuilder tempBuilder = new StringBuilder();
String longestStringToShort="";
int count=0;
//Find abbreviations for terms with multiple words
for(int k=0;k<list.size()-i;k++){
tempBuilder.append(" "+listUpperCase.get(i+k));
if(k==0) tempBuilder.deleteCharAt(0);
String value = map.get(tempBuilder.toString());
if (value!=null){
longestStringToShort = value;
count = k;
}
}
if (!longestStringToShort.equals("")){
builder.append(" "+longestStringToShort);
i=i+count;
}
else builder.append(" "+list.get(i));
}
builder.deleteCharAt(0);
return builder.toString();
}
AUTOMATIC GAIN CONTROL
withAGC
andAUTOMATIC
withAUTO
? \$\endgroup\$CONTROL
example... thanks for the clarification anyways. :) \$\endgroup\$