0

Consider a map as below:

Map("PDF","application/pdf")
Map("XLSX","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
Map("CVS","application/csv")
....

There is an export method which gets the export button name and find the export type and application content type

public void setExport(String exportBtn) {       
        for (String key : exportTypes.keySet()) {
            if (exportBtn.contains(key)) {
                this.export = key;
                this.exportContentType = exportTypes.get(key);
                LOG.debug("Exporting to {} ", this.export);
                return ;
            }
        }
    }

This method can be called as

setExport("PDF") >> export=PDF, exportContentType=application/pdf
setExport("Make and PDF") >> PDF, exportContentType=application/pdf
setExport("PDF Maker") >> PDF, exportContentType=application/pdf

I am not feeling good with this approch! At least I think there is some libs, for example in StringUtils, which can do something like:

String keys[]={"PDF","XLSX","CVS"};
String input="Make the PDF";
selectedKey = StringUtils.xxx(input,keys);

This can some how simplify my method.

But I could not find anything. Any comments?!

Alireza Fattahi
  • 42,517
  • 14
  • 123
  • 173

2 Answers2

0

Map is the easy and best implementation to store key-value pairs.

Why cannot you directly use the get method of map with key?

exportContentType = exportTypes.get(exportBtn);
if(exportContentType !=null || exportcontentType.isEmpty())
   throw error;
else
 export = exportBtn;
Abhijith Nagarajan
  • 3,865
  • 18
  • 23
  • The exportBtn could be "Make PDF", "Export to PDF" it is not always "PDF" ! – Alireza Fattahi Nov 27 '13 at 13:58
  • Sorry for the incomplete answer. The code that you have written is the way to do what you want. As such there are library methods which would help you doing it. The only change I would prefer do is by iterating over entryset than keyset. – Abhijith Nagarajan Nov 27 '13 at 14:02
0

You could use Regex to solve this issue, something like this:

final Pattern pattern = Pattern.compile("(PDF|XLSX|CVS)");
final Matcher matcher = pattern.matcher("Make the PDF");

if (matcher.find()) {
  setExportType(matcher.group());
}

You then need to create the pattern procedurally to include all keys once, and of course use the button's name instead of "Make the PDF".

TwoThe
  • 13,879
  • 6
  • 30
  • 54