Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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(" ,")));
like image 870
serah Avatar asked Dec 02 '25 23:12

serah


1 Answers

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.

like image 155
Ravindra Ranwala Avatar answered Dec 05 '25 12:12

Ravindra Ranwala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!