93

I want to concatenate an ArrayList with commas as separators. I found this answer, stating it's possible to use String.join in Java.

When I try to use this however, Android Studio gives the following error:

Cannot resolve method 'join(java.lang.String, java.lang.String, java.lang.String, java.lang.String)'

Is there a good, concise alternative for Android Studio (instead of using a for loop)?

Community
  • 1
  • 1
TheLeonKing
  • 3,501
  • 7
  • 32
  • 44

3 Answers3

217

You can use TextUtils.join instead:

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

(String.join was added in Java 8, which is why you can't use it in Android.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 3
    To save a few clicks to non Android Studio users: `import android.text.TextUtils` – Peter Jankuliak Nov 21 '18 at 10:29
  • Using TextUtils may cause problem with unit test. In that case use a function from here : https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/text/TextUtils.java – Subin Jul 04 '19 at 19:15
  • 1
    @Subin: What kind of problem? And why link to TextUtils as an alternative to TextUtils? I'm afraid your comment isn't really clear. – Jon Skeet Jul 04 '19 at 20:22
  • @JonSkeet Cause this problem : https://stackoverflow.com/q/35763289/1372424 Solution from here : https://medium.com/@okmanideep/dont-create-that-stringutils-to-unit-test-your-android-class-8ab32af34e84 – Subin Jul 05 '19 at 21:02
  • 2
    @Subin: Right, so *specifically* if you're using Mockito. And note that the solution is a matter of copying the TextUtils source into your test project. – Jon Skeet Jul 05 '19 at 21:22
7
String[] List ={"<html>","<body>","<title>"};
String abc;       
abc =TextUtils.join("\n", List);
textmsg.getText().insert(textmsg.getSelectionStart(), abc);

result:

<html>
<body>
<title>
V-rund Puro-hit
  • 5,518
  • 9
  • 31
  • 50
BREI
  • 101
  • 2
  • 4
3

You can use this

TextUtils.join(", ", your_list);
Zeeshan Ahmed
  • 1,179
  • 2
  • 13
  • 30