8

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.

Cosmin Cosmin
  • 1,526
  • 1
  • 16
  • 34

2 Answers2

15

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(", ")));
Tomasz Szymulewski
  • 2,003
  • 23
  • 23
  • I know this is an old answer, but does anyone know how efficient these are? I know streams have some overhead to create but work realty well when dealing with big collections. Would this solution be efficient if my collection size was less than 1000, something like 20-100? – Spik330 Jul 24 '19 at 18:41
3

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"));
Bohemian
  • 412,405
  • 93
  • 575
  • 722