gpt4 book ai didi

Java/Android : Append multiple strings, 如果字符串为空则跳过

转载 作者:行者123 更新时间:2023-11-29 04:36:21 25 4
gpt4 key购买 nike

我有四个字符串需要 append 。

String food = extras.getString("food");
String file = extras.getString("file");
String parcel = extras.getString("parcel");
String others = extras.getString("others");

String itemList = new StringBuilder(food).append("\n")
.append(file).append("\n")
.append(parcel).append("\n")
.append(others).toString();

如果我选择FoodFile,此代码将打印

Food
File
null
null

由于 Parcel 和 Others 没有值(null),如何让它打印如下?

Food
File

我尝试使用 if else 但它会太长(14 种可能性)。有没有其他方法可以让它更短更有效?

最佳答案

Java 8 的流式传输功能提供了一种非常巧妙的方式来做到这一点:

String itemList =
Stream.of(food, file, parcel, others)
.filter(Objects::nonNull)
.collect(Collectors.joining("\n"));

编辑:
对于旧版本的 java,您可以使用传统的 for 循环做一些类似的事情,尽管它会更笨重:

StringBuilder sb = new StringBuilder();
for (String s : Arrays.asList(food, file, parcel, others)) {
if (s != null) {
sb.append(s).append('\n');
}
}
String itemList = sb.toString();

关于Java/Android : Append multiple strings, 如果字符串为空则跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41315439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com