Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to String mapping using Spring?

From external system I receive String representation of some abbreviations and I have to make transformation(conversion) to another String for example:

"O" -> Open
"C" -> Closed
"E" -> Exit

For Object to Object conversion I was using Spring Custom COnverter

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 can't create String to String converter. I do not want to use external mapping library only Spring capabilities. But I can't do this. The simplest thing that I can do is switch

String input = "O";
String result = null;
switch(input){
 case "O": result ="Open"
 break;
case "C": result ="Close"
 break;
....

In matter of fact I have to do over 100 mapings. Can Spring offer better solution?

like image 419
Xelian Avatar asked Feb 13 '26 04:02

Xelian


1 Answers

When you don't have any logic to execute in switch-case, you can use a static HashMap<String,String>

  static HashMap<String,String> map = new HashMap<>();
  static
  {
      map.put("O","Open");
      map.put("C","Close");
      .....................

  }

Instead of switch-case just use

     map.get(input);

If you are suing Java 8, you can even use

    map.getOrDefault(input,"");
like image 61
Karthik Avatar answered Feb 14 '26 17:02

Karthik