String to String using Spring?
From the external system, I am getting a string representation of some abbreviations and I have to do the conversion (conversion) to another string, for example:
"O" -> Open
"C" -> Closed
"E" -> Exit
I used Spring Custom COnverter to convert Object to Object
import org.springframework.core.convert.converter.Converter;
public class Converter<Source, Target> implements Converter<Source, Target>
public final Target convert(@Nonnull Source source) {
...
}
But I cannot create a String to String converter. I don't want to use only Spring external display libraries. But I cannot do this. The easiest thing I can do is switch
String input = "O";
String result = null;
switch(input){
case "O": result ="Open"
break;
case "C": result ="Close"
break;
....
In fact, I have to make over 100 maps. Can Spring suggest a better solution?
+3
source to share
1 answer
If there is no logic in the switch, you can use static HashMap<String,String>
static HashMap<String,String> map = new HashMap<>();
static
{
map.put("O","Open");
map.put("C","Close");
.....................
}
Instead of a wiring closet, just use
map.get(input);
If you are applying for Java 8 you can even use
map.getOrDefault(input,"");
+4
source to share