How can I use Joiner, to join only specific properties?

3k views Asked by At

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?

1

There are 1 answers

3
meskobalazs On BEST ANSWER

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(); }
}));