Skip to content

Instantly share code, notes, and snippets.

@bmchild
Created March 16, 2012 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmchild/2052123 to your computer and use it in GitHub Desktop.
Save bmchild/2052123 to your computer and use it in GitHub Desktop.
Join a Collection on any POJO with a Data Extractor
com.bmchild;
//imports
public class CallingMyCollectionsUtil {
private class Pojo {
private String field;
public String getField() {
return field;
}
public String setField(String field) {
this.field = field;
}
}
public void main(Sring[] args) {
Pojo pojo1 = new Pojo();
pojo1.setField("AWS");
Pojo pojo2 = new Pojo();
pojo2.setField("SOME");
List<Pojo> pojos = new ArrayList<Pojo>();
pojos.add(pojo1);
pojos.add(pojo2);
String emailString = MyCollectionsUtil.join(pojos, "->", new DataExtractor<Pojo>() {
public String val(Pojo obj) {return obj.getField; }
});
}
}
com.bmchild.util;
public class MyCollectionsUtil {
public static <T> String join(List<T> objs, String delimiter, MyDataExtractor<T> dataExtractor) {
StringBuilder string = new StringBuilder();
if(!CollectionUtils.isEmpty(objs)) {
int i = 0;
int size = objs.size();
for (T obj : objs) {
string.append(dataExtractor.val(obj));
if(i < size -1) {
string.append(delimiter);
}
i++;
}
}
return string.toString();
}
}
com.bmchild.extractor;
public interface MyDataExtractor<T> {
/**
* Extracts the desired value from the given object.
*
* @param obj The object.
* @return The desired value extracted from the object.
*/
String val(T obj);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment