Search code examples
javadesign-patternsjavabeans

Better Design Pattern?


I have myArrayList that already have values in it. For this example lets say there are only two elements in it(firstName and lastName). I need to get values from myArrayList and compare them to String and if it matches then get value from the bean and put it into map:

        Map<String,String> myMap;
        for(String element: myArrayList){
               if(element.equalsIgnoreCase("firstName")){
                   myMap.put("firstName", bean.getFirstName());
               }else if(element.equalsIgnoreCase("lastName")){
                   myMap.put("lastName", bean.getLastName());
               }
        }

The problem is when you have thirty-forty elements in myArrayList you will have performance issues(I assume), and it just doesn't feel right.

I tried this:

        String name = null;
        String value = null;
        for(int i = 0; i < myArrayList.size(); i++){
            name = myArrayList.get(i);
            value = bean.get(name);
            myMap.put(name, value);
        }

But the line "value = bean.get(name);" is saying that method get(String) is undefined in bean class, indeed we don't have such method in bean class, it has only standard getter and setter methods:

public class Bean implements Serializable {
    private String firstName;
    private String lastName;

    public String getFirstName(){
        return firstName;
    }

    public void setFirstName(String firstName){
        this.firstName = firstName;
    }

    public String getLastName(){
        return lastName;
    }

    public void setLastName(String lastName){
        this.lastName = lastName;
    }

}

Now I am thinking how I could come up with some design pattern that optimizes my logic and doesn't affect performance of the code. Please feel free to ask questions, I will edit if you need more info. Any help is greatly appreciated. Thanks.

Edit: shmosel's answer was pretty good for me, thank you all for your help! Cheers!


Solution

  • @HankD and @Natalia have offered some valid solutions, but another option I don't see mentioned is refactoring Bean to support a get(String) method:

    public class Bean implements Serializable {
        private Map<String, String> properties = new HashMap<>();
    
        public String get(String property) {
            return properties.get(property);
        }
    
        public void set(String property, String value) {
            properties.put(property, value);
        }
    
        public String getFirstName(){
            return get("firstName");
        }
    
        public void setFirstName(String firstName){
            set("firstName", firstName);
        }
    
        public String getLastName(){
            return get("lastName");
        }
    
        public void setLastName(String lastName){
            set("lastName", lastName);
        }
    
    }