guava - Java: possible transformation of List of objects to List of strings -


i have bunch of manager classes manage different objects state, country , on. getobjects() method returns list of such objects, values of these lists appended in different methods following ones:

//states - statemanager.java public string getstatemsg() {     stringbuilder msg = new stringbuilder();     if (states != null) {         (state state : states.getobjects()) {             msg.append(state.getstatecd())).append(" ");         }     }     return msg.tostring().trim(); }  //codes - codemanager.java public string getcodemsg() {     stringbuilder msg = new stringbuilder();     if (codes != null) {         (code code :  codes.getobjects()) {             msg.append(code.getcd()).append(" ");         }     }     return msg.tostring().trim(); }  //countries - countrymanager.java public string getcountriesmsg() {     stringbuilder msg = new stringbuilder();     if (countries != null) {         (country country : countries.getobjects()) {             msg.append(countries.get(country.getcountrycd())).append(" ");         }     }     return msg.tostring().trim(); } 

there's obvious code duplication , want make general solution method takes collection (retrieved getobjects()) , returns list of strings.

i found guava can make sort of collection transformations 1 type another. classes in example (state, code, country) not share general interface. other hand, method take collection of objects , method name retrieve value of specific object field, means usage of reflection isn't idea.

as result have question, possible avoid described code duplication , make utility method take collection of objects , return collection of strings?

if don't have java 8, use generics , guava function:

public static <t, u> string getgenericmsg(list<t> genericlist, function<t, u> function) {     stringbuilder msg = new stringbuilder();     if (genericlist != null) {         (t genericobject : genericlist) {             msg.append(function.apply(genericobject)).append(" ");         }     }     return msg.tostring().trim(); }   private static function<state, string> state_to_string = new function<state, string>() {     public string apply(state input) {         return input.getstatecd();     } };  private static function<code, string> code_to_string = new function<code, string>() {     public string apply(code input) {         return input.getcd();     } };  private static function<country, string> country_to_string = new function<country, string>() {     public string apply(country input) {         return input.getcountrycd();     } }; 

finally client code:

public void yourclientmethod() {     getgenericmsg(states, state_to_string);     getgenericmsg(codes, code_to_string);     getgenericmsg(countries, country_to_string); } 

Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -