Search code examples
javalistif-statementreadability

Get field details inside list without large if else condition in Java


I have a List of objects. The list is quiet big. All the values are String. Currently I'm doing for each loop with if condition. But readability will not be good and it becomes lengthy. Following is the code snippet:

List<Fields> fieldList = <(device,value),(quantity,value),(position,value),(note,value),(model,value),(lotNumber,value)...>;    
for(Fields fl : fieldList)
{
 if(fl.name.equals("device"))
  doSomething1();
else if(fl.name.equals("quantity"))
 doSomething2();
//This goes on
}

Please suggest a better way. Note: Time is not a factor.


Solution

  • From java 7 you can use the switch case statement also with a String. You can also group different conditions (as "device" and "anotherDevice" in the following code):

    ...
    switch (f1.name) {
        case "device":
        case "anotherDevice":
            doSomething1();
            break;
        case "quantity":
            doSomething2();
            break;
        default:
            doSomething3();
    }
    

    Edited with a new different approach: If you are not limited to a list of String you can use another approach. Define an interface Worker

    public interface Worker {
        public void work();
    }
    

    Define n classes that implements Worker

    public class PrintWorker implements Worker {
        public void work() {
            System.out.println("Print something");
        }
    }
    
    public class AnotherPrintWorker implements Worker {
        public void work() {
            System.out.println("A different action here");
        }
    }
    

    Create the list with objects of type Worker

    List<Worker> workers = new ArrayList<Worker>();
    ...
    workers.add(new PrintWorker());
    workers.add(new AnotherPrintWorker());
    ...
    for (Worker worker : workers) {
        worker.work();
    }
    

    As you see in this case the for loop is very simple and easy to read. A specific implementation of work() method must be read in each class implementing the Worker interface.