Groovy中移除逗号分隔字符串内null值的方法咨询
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

