Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of Person object into a separated String by getName() property of Person object

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.

like image 561
Cosmin Cosmin Avatar asked Jul 04 '12 12:07

Cosmin Cosmin


2 Answers

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(", ")));
like image 75
Tomasz Szymulewski Avatar answered Oct 09 '22 12:10

Tomasz Szymulewski


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"));
like image 38
Bohemian Avatar answered Oct 09 '22 11:10

Bohemian