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

2

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.

Liaoyang answered 4/7, 2012 at 12:48 Comment(3)
#1515937 more information here how to use the join method.Fryer
well yeah, but I don't have String, I have Person :)Liaoyang
Create your own utility method that uses BeanUtils.getArrayProperty() and transforms the checked exceptions into runtime ones.Unsparing
A
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(", ")));
Agreement answered 23/7, 2015 at 11:28 Comment(1)
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?Broadnax
C
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"));
Contortionist answered 4/7, 2012 at 13:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.