如何使用 Joiner 仅加入特定属性?
How can I use Joiner, to join only specific properties?
假设我有这个 class:
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"
我该怎么做?
"old-school"解决方法:
您可以使用内置的标准 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.on(", ").join(Iterables.transform(myList, new Function<MyClass, String>() {
public String apply(MyClass object) { return object.getPropertyOne(); }
}));
假设我有这个 class:
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"
我该怎么做?
"old-school"解决方法:
您可以使用内置的标准 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.on(", ").join(Iterables.transform(myList, new Function<MyClass, String>() {
public String apply(MyClass object) { return object.getPropertyOne(); }
}));