Let's say I have this class:
public class MyClass {
private String propertyOne;
private String propertyTwo;
// getters setters...
}
Now, in my test method, I am trying something like:
List<MyClass> myList = myListDao.findAll();
String aStringFullOfPropertyOnesOfAllMyObjects = Joiner.on(", ").join(myList.iterator());
The String
, I want to get back is something like:
"propOneOfObjectOne, propOneOfObjectTwo, propOneOfObjectThree"
How can I do this?
The "old-school" solution:
You could use the built-in standard StringBuilder:
StringBuilder builder = new StringBuilder();
Iterator<MyClass> iter = myList.iterator();
for (MyClass object = iter.next(); iter.hasNext();) {
builder.append(object.getPropertyOne());
if (iter.hasNext()) {
builder.append(", ");
}
}
String result = builder.toString();
Using Joiner:
Using Joiner
from the linked answer:
Joiner.on(", ").join(Iterables.transform(myList, new Function<MyClass, String>() {
public String apply(MyClass object) { return object.getPropertyOne(); }
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With