Best way to suffix value to a string if it matches a condition and generate a comma separated list of the values in a list

serah :

What is the best way to do the below in Java 8.

I have a list of ColumnInfo objects,

ColumnInfo CLASS has below members

String name
Class<?> type
Object value

I want to iterate list of ColumnInfo objects and if any of them is of type String.class I want to suffix "IS A STRING" to the column name , for other columns I want to return column name as is, the return value should be a comma separated string. The comma separated string should maintain the order of items as is in the incoming List of ColumnInfo objects.

So, if I have column info objects as below

{order_code , Integer.class, 10}
{order_city, String.class ,"france"}
{is_valid, Boolean.class, true}

expected output

order_code, order_city IS A STRING, is_valid

Below is my approach, Is there a better way to do this?

String commaSepStr = columnInfos.stream()
            .map(f -> {
                String retValue = isString(f)? f.getName()+ " IS A STRING" : f.getName();
                return retValue;
            }).collect(Collectors.joining(" ,")));
Ravindra Ranwala :

You may do it like so,

String resultStr = columnInfoList.stream()
    .map(ci -> ci.getType() == String.class ? ci.getName() + " IS A STRING" : ci.getName())
    .collect(Collectors.joining(", "));

You don't need to assign it to a variable and return. Rather you can directly return it. Also the implementation of the isString method seems not necessary to me since it can be done inline. So it is fair for me to keep this as the answer.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=80198&siteId=1