我如何使用Joiner,仅加入特定属性?

时间:2015-02-02 10:51:53

标签: java guava joiner

假设我有这门课程:

public class MyClass {
    private String propertyOne;
    private String propertyTwo;
    // getters setters...
}

现在,在我的测试方法中,我尝试的是:

List<MyClass> myList = myListDao.findAll(); 
String aStringFullOfPropertyOnesOfAllMyObjects =  Joiner.on(", ").join(myList.iterator());

String,我想回来的是:

"propOneOfObjectOne, propOneOfObjectTwo, propOneOfObjectThree"

我该怎么做?

1 个答案:

答案 0 :(得分:12)

&#34;老派&#34;溶液

您可以使用内置的标准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();

使用Joiner:

使用链接答案中的Joiner

Joiner.on(", ").join(Iterables.transform(myList, new Function<MyClass, String>() {
    public String apply(MyClass object) { return object.getPropertyOne(); }
}));