madhu_karnati
madhu_karnati

Reputation: 795

MULTIPLE if else CONDITIONS in java code

My text file has this:

Apple IS A fruit
BANABA=fruit
HERO=fruit
TOYOTA 784YUT
USAIRWAYS canada
METROBUS=newyork

TOYOTA 784YUT is the only text in that line.

FileReader file = new FileReader("C:\\FILEREADER\\MockupData.txt");
BufferedReader br = new BufferedReader(file);
String line;
try {
    while ((line = br.readLine()) != null) {
        if (line.contains("METRO")) {
            String Id = myPrivateMethodToHandleThisLine1(line);
            //do something with this id.                        
        } else if (line.contains("TOYOTA")) {
            String Id2 = myPrivateMethodToHandleThisLine2(line);
            //do something with this id.    
        } else if (line.contains("HERO")) {
            String Id3 = myPrivateMethodToHandleThisLine3(line);
            //do something with this id.                } .
        .
        .(some more if/else conditions)
        .
        .
        .
} catch (IOException e) {
    e.printStackTrace();
}
  .....remaing code.

My Problem is simple, I am reading text from a file line by line. Based on the input line I get, I'll call handling method.

I want to implement this code best in performance. I don't want to keep multiple if/else conditions. Need suggestions.

NOT USING JAVA 1.7

Upvotes: 0

Views: 250

Answers (1)

Eran
Eran

Reputation: 393821

I suggest you define a Map whose keys are "METRO", "TOYOTA", etc... and its values are the methods you wish to execute for each key. The methods can be represented by a functional interface (even if you are not using Java 8).

Now, in order to use the map, you'll need a way to extract the key of a given line, so it would be best if each line would start with the key followed by some delimiter (Example : TOYOTA,field2,field3,...).

Example :

public interface ProcessLineInterface
{
    public void processLine (String line);
}

Map<String, ProcessLineInterface> map = new HashMap<String, Runnable>();

map.put ("METRO", new ProcessLineInterface () {
           public void processLine (String line)
           {
               myPrivateMethodToHandleThisLine1(line);
           }
         });
map.put ("TOYOTA", new ProcessLineInterface () {
           public void processLine (String line)
           {
               myPrivateMethodToHandleThisLine2(line);
           }
         });
map.put (...);
...

while ((line = br.readLine()) != null) 
{
    ProcessLineInterface pline = map.get(extractKey(line));
    if (pline != null) {
        pline.processLine(line);
    }
}

Upvotes: 2

Related Questions