Android中String.join的替代选择?


79

我想用逗号作为分隔符连接一个ArrayList。我找到了这个答案,说明可以String.join在Java中使用。

但是,当我尝试使用此功能时,Android Studio出现以下错误:

无法解析方法'join(java.lang.String,java.lang.String,java.lang.String,java.lang.String)'

Android Studio是否有一个好的简洁的替代方法(而不是使用for循环)?


TextUtils.join()也许吗?
mjp66

试试StringUtils.join
Bhargav Thanki 2015年

Answers:


183

您可以TextUtils.join改用:

String result = TextUtils.join(", ", list);

String.join已在Java 8中添加,这就是为什么您不能在Android中使用它的原因。)


3
要将点击保存给非Android Studio用户:import android.text.TextUtils
Peter Jankuliak,

使用TextUtils可能会导致单元测试出现问题。在这种情况下,请使用以下函数:android.googlesource.com/platform/frameworks/base
refs

1
@Subin:什么样的问题?以及为什么链接到TextUtils作为TextUtils的替代方法?恐怕您的评论不清楚。
乔恩·斯基特

:@JonSkeet导致此问题stackoverflow.com/q/35763289/1372424从这里解决方法:medium.com/@okmanideep/...
李苏滨

2
@Subin:是的,特别是如果您正在使用Mockito。并请注意,解决方案是将TextUtils源复制到测试项目中。
乔恩·斯基特

7
String[] List ={"<html>","<body>","<title>"};
String abc;       
abc =TextUtils.join("\n", List);
textmsg.getText().insert(textmsg.getSelectionStart(), abc);

结果:

<html>
<body>
<title>

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.