Is there a XXXUtils
where I can do
String s = XXXUtils.join(aList, "name", ",");
where "name"
is a JavaBeans property from the object in the aList
.
I found only StringUtils
having join
method, but it only transforms a List<String>
into a separated String
.
Something like
StringUtils.join(BeanUtils.getArrayProperty(aList, "name"), ",")
that's fast and worths using. The BeanUtils throws 2 checked exceptions so I don't like it.
Java 8 way of doing it:
String.join(", ", aList.stream()
.map(Person::getName)
.collect(Collectors.toList())
);
or just
aList.stream()
.map(Person::getName)
.collect(Collectors.joining(", ")));
I'm not aware of any, but you could write your own method using reflection that gives you the list of property values, then use StringUtils
to join that:
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;
}
To get your join, do this:
List<Person> people;
String nameCsv = StringUtils.join(getProperties(people, "name"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With