You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Groovy中移除逗号分隔字符串内null值的方法咨询

Direct String Handling Solutions to Avoid Nulls in Groovy Concatenation

Hey there! Since you want to stick to direct string processing instead of relying on arrays/lists, here are a couple of straightforward approaches to keep those annoying null values out of your final concatenated string:

1. Conditional Ternary Concatenation with Trailing Cleanup

Use Groovy's ternary operator to conditionally add each variable only if it’s non-null, then clean up any leftover trailing comma and space:

def presentationType = "${feedDisplayType ? feedDisplayType + ', ' : ''}" +
                       "${moduleType ? moduleType + ', ' : ''}" +
                       "${cellType ?: ''}"
// Remove trailing ", " if it exists
presentationType = presentationType.replaceAll(/, $/, "")

This checks each variable: if it’s not null, we append the value plus a comma-space; if it is null, we add an empty string. The final regex strip ensures we don’t end up with a hanging comma if the last non-null variable isn’t cellType.

2. Explicit Step-by-Step Appending

If you prefer readability over conciseness, build the string incrementally with checks for existing content before adding separators:

def presentationType = ""
if (feedDisplayType != null) {
    presentationType += feedDisplayType
}
if (moduleType != null) {
    presentationType += (presentationType ? ", " : "") + moduleType
}
if (cellType != null) {
    presentationType += (presentationType ? ", " : "") + cellType
}

This method adds a comma-space only if the string already has content, so you’ll never get leading or trailing commas—even if multiple variables are null.

Quick Side Note (Even Though You Mentioned Arrays Are Easier)

Just for completeness, Groovy has a super concise list-based approach if you ever change your mind:

def presentationType = [feedDisplayType, moduleType, cellType].findAll().join(", ")

But since you asked for direct string handling, the first two options fit your request perfectly. Both will handle edge cases like all variables being null (resulting in an empty string) or mixed null/non-null values with proper comma separation.

内容的提问来源于stack exchange,提问作者rasilvap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:02:52