Cos*_*min 8 java apache-commons separator apache-stringutils apache-commons-collection
有XXXUtils我可以做的地方
String s = XXXUtils.join(aList, "name", ",");
Run Code Online (Sandbox Code Playgroud)
哪个"name"是来自对象的JavaBeans属性aList.
我发现只有StringUtils具有join的方法,但它只是一个变换List<String>成一个分离String.
就像是
StringUtils.join(BeanUtils.getArrayProperty(aList, "name"), ",")
Run Code Online (Sandbox Code Playgroud)
这很快,值得使用.BeanUtils会抛出2个已检查的异常,所以我不喜欢它.
Tom*_*ski 14
Java 8的做法:
String.join(", ", aList.stream()
.map(Person::getName)
.collect(Collectors.toList())
);
Run Code Online (Sandbox Code Playgroud)
要不就
aList.stream()
.map(Person::getName)
.collect(Collectors.joining(", ")));
Run Code Online (Sandbox Code Playgroud)
我不知道有什么,但您可以使用反射编写自己的方法,为您提供属性值列表,然后使用StringUtils它来加入:
public static <T> List<T> getProperties(List<Object> list, String name) throws Exception {
List<T> result = new ArrayList<T>();
for (Object o : list) {
result.add((T)o.getClass().getMethod(name).invoke(o));
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
要加入,请执行以下操作:
List<Person> people;
String nameCsv = StringUtils.join(getProperties(people, "name"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3972 次 |
| 最近记录: |