简体   繁体   中英

Java String appending with comma as a separator

I have a requirement where I need to append multiple values from multiple web service calls into one final string with comma as a separator.

Some of the values might be null, in that case I need to check for not null and then append it as empty string. If there is no value for one of the string, comma should not get appended.

Please help me resolving this. here is the code what I did.

                StringBuilder sb = new StringBuilder();
            if (usersList.totalCount != 0 && usersList.totalCount >= 1) {
                logger.info("usersList.totalCount ----->"
                        + usersList.totalCount);
                for (KalturaUser user : usersList.objects) {
                    if (user.id != null) {
                        sb.append(userId);
                    }
                    if (user.firstName != null) {
                        sb.append(",").append(userFirstName);
                    }
                    if (user.lastName != null) {
                        sb.append(",").append(user.lastName);
                    }
                    if (user.email != null) {
                        sb.append(",").append(user.email);
                    }
                    if (user.roleNames != null) {
                        sb.append(",").append(user.roleNames);
                    }
                    if (user.partnerData != null) {
                        sb.append(",").append(user.partnerData);
                    }

                }
                System.out.println(sb);
            }

Thanks, Raji

I think you are looking for something like this:

public static String asString(Object value) {
    return value == null ? "" : value.toString();
}

for (KalturaUser user : usersList.objects) {
    sb.append(asString(user.id));
    sb.append(",").append(asString(user.firstName));
    sb.append(",").append(asString(user.lastName));
    sb.append(",").append(asString(user.email));
    sb.append(",").append(asString(user.roleNames));
    sb.append(",").append(asString(user.partnerData));
}

Well, in your tests like

if (user.id != null) {
    sb.append(userId);
}

you are checking user.id but appending userId . These are two different variables.

You should probably change it into

if (user.id != null) {
    sb.append(user.id); //instead of sb.append(userId);
}

目前尚不清楚您的问题是什么,但是如果您正在寻找更好的方法或其他方法,我发现最好追加到List <String>,然后使用StringUtils.join生成最终字符串。

I would do something like that. It's based on Java8 streams, but here you don't need to do the non-null check on every property( .filter does this for you). I assumed that users.object is an array list, if it's not you might need to convert it into stream in other way

if (userList.totalCount > 0) {
    logger.info("usersList.totalCount ----->" + usersList.totalCount);

    String result = userList
                    .objects
                    .stream()
                    .map(user -> {
                        return Stream.of(user.firstName, user.id, user.lastName, user.email, user.roleNames, user.partnerData) //get the properties you need into the stream
                                        .filter(property -> property != null) // filter out null properties
                                        .collect(Collector.joining(",")); //join them by comma
                    })
                    .collect(Collector.joining(",")); //join user strings with comma

    System.out.println(result);
}

You can use a class from a google library called Joiner.

String concatenedString = Joiner.on(",").skipNulls().join(itemToAdd);

You can find this class on google-collections-1.0.jar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM