Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

guava

joiner

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?

like image 440
Koray Tugay Avatar asked Feb 02 '15 10:02

Koray Tugay


1 Answers

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(); }
}));
like image 162
meskobalazs Avatar answered Oct 05 '22 23:10

meskobalazs