3

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?

4
  • 1
    Is this mapping fixed? Commented Jul 8, 2015 at 19:52
  • Yes. All mappings are fixed and we know for them. Commented Jul 9, 2015 at 5:09
  • Did you consider using a static HashMap instead of switch case? Commented Jul 9, 2015 at 5:10
  • It's interesting I have not thought about it Commented Jul 9, 2015 at 5:11

1 Answer 1

4

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,"");
Sign up to request clarification or add additional context in comments.

6 Comments

It might be clever to declare the map not inside the static initializer block.
@Tom you mean to just remove static or declare the map outside static?
Move the line HashMap<String,String> map = new HashMap<>(); outside of the static block. Currently your map is bound to that block and when the execution of that block is finished, then this map will be removed.
@Tom oh yeah! I missed that. Thank you :)
Don't forget that keyword static in front of the variable ;).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.