Created
March 16, 2012 19:39
-
-
Save bmchild/2052123 to your computer and use it in GitHub Desktop.
Join a Collection on any POJO with a Data Extractor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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