1

I have an ArrayList<String> and I need to loop through it, and what is present in the list has to perform certain actions. I wish to optimize the iteration and comparisons, can it be done?

My code:

Person class (includes getters and setters):

private String employeeID;

private String firstName;

private String lastName;

private String gender;

private String mobileNo;

private String emailID;

My computed ArrayList, myList- [firstName, gender, mobileNo, emailID]. How do I optimize my logic shown below to avoid so many if conditions?

Person p =new Person ();
for(String element:myList)
        {
       if("employeeid".equalsIgnoreCase(element))
            {
                p.setemployeeID("");
            }
       if("firstname".equalsIgnoreCase(element))
            {
                p.setfirstName("");
            }
       if("lastName".equalsIgnoreCase(element))
            {
                p.setlastName("");
            }
       if("gender".equalsIgnoreCase(element))
            {
                p.setgender("");
            }
       if("mobileno".equalsIgnoreCase(element))
            {
                p.setMobileNo("");
            }
       if("emailid".equalsIgnoreCase(element))
            {
                p.setEmailID("");
            }
        }
4
  • 2
    first of all, you could use if - else if, instead of eacht time an if. You can also switch on them. Commented Feb 3, 2016 at 9:30
  • Suggested reading: Java If-then-Else statements, Java switch statement, and a bit of an extra - Java Code formatting conventions Commented Feb 3, 2016 at 9:41
  • seriously you want to use a list? Not being able to see logic behind it. Commented Feb 3, 2016 at 9:41
  • 2
    It would be worth while explaining what it is you're doing. Optimizing the loop doesn't seem valuable since it could probably be replaced with a better approach. Commented Feb 3, 2016 at 9:43

3 Answers 3

3

The compiler is able to optimize switch statements into a lookup table and perform compile-time checking for literals when dealing with enumerations. That being said, you should always use switch statements for over 3 comparisons. Hence your code becomes-

private static final String EMPLOYEE_ID = "employeeid";
private static final String FIRST_NAME = "firstname";
private static final String LAST_NAME = "lastName";
private static final String GENDER = "gender";
private static final String MOBILE_NO = "mobileno";
private static final String EMAIL_ID = "emailid";

Person p =new Person ();
for(String element: myList) {
switch (element.toLowerCase()) {
  case EMPLOYEE_ID: p.setemployeeID("");
    break;
  case FIRST_NAME: p.setfirstName("");
    break;
  case LAST_NAME: p.setlastName("");
    break;
  case GENDER: p.setgender("");
    break;
  case MOBILE_NO: p.setMobileNo("");
    break;
  case EMAIL_ID: p.setEmailID("");
    break;
}

}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for a pleasing way.
Thanks for the restoration:).
This isn't even an ENUM.
I never said, that we can only use an enum in switch statements. We can also use final variables as well as they don't change there values which were assigned to them. The java compiler automatically replaces these variables with the corresponding constant values, which you have used in your answer.
Anyway I added a proper Enum to my answer as a reference
3

There isn't so much to be done here, but maybe a switch can be more aesthetically pleasing. Though you will have to make sure your input is either only lowercase or only uppercase:

for(String element:myList) {
    switch (element.toLowerCase()){
        case "employeeid": p.setemployeeID(""); break;
        case "firstname" : p.setfirstname(""); break;
        .
        .
        .

    }
}

If you decide you wish to keep your if design, you should definitely use if-else so you won't have to run through all your ifs in every iteration.

And as a final note, this probably isn't the best way to design whatever it is you are trying to do. You should consider something of a more OO nature, like passing the parameters of a Person object to the constructor when you instantiate a Person object.

Edit: I see you want to use an Enum, you would want to actually define it like so:

public enum MyEnum {
    EMPLOYEE_ID("employeeid"),
    FIRST_NAME("firstname")
    .
    .
    .
    ;

    private final String text;

    private MyEnum(final String text) {
        this.text = text;
    }

    @Override
    public String toString() {
        return text;
    }
}

2 Comments

I think you haven't used MyEnum anywhere in your code.
I added it as an edit after. See the revisions. So it hardly justifies a downvote, but sure
0

I didn´t test, but (if the string and the method name are the same) you could use reflection, something like this:

Person p = new Person();
for(String element : myList) {

    // method params
    Class[] paramTypes = new Class[1];
    paramTypes[0] = String.class;

    // method
    String methodName = "set" + element.indexOf(0,1).toUpperCase() + element.indexOf(1);
    Method m = c.getDeclaredMethod(methodName, paramTypes);

    // call method
    m.invoke(p, "");
}

Comments

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.