dimanche 27 août 2017

Populate List from pojo in given order

I have a POJO object having few fields and a list of string. We have to create a list of object using field values of pojo, in exactly same order as of list of string. Right now I am calling list.add with pojo getters while looping on list of String-

public class ResultSet {private String field1;
private String field2;
private String field3;
private String field4;


public List<Object> populateResultList(List<String> list) {
    List<Object> resultSet = new ArrayList<>();
    for (String filedName : list) {
        if ("Field1".equalsIgnoreCase(filedName)) {
            resultSet.add(getField1());
        } else if ("Field2".equalsIgnoreCase(filedName)) {
            resultSet.add(getField2());
        } else if ("Field3".equalsIgnoreCase(filedName)) {
            resultSet.add(getField3());
        } else if ("Field4".equalsIgnoreCase(filedName)) {
            resultSet.add(getField4());
        }
    }
    return resultSet;
}


public String getField1() {
    return field1;
}

public String getField2() {
    return field2;
}

public String getField3() {
    return field3;
}

public String getField4() {
    return field4;
}}

Is there any better way to achieve this as its lot of boilerplate code.

Aucun commentaire:

Enregistrer un commentaire