Arraylist of strings into one comma separated string

前端 未结 4 611
暗喜
暗喜 2021-01-15 11:57

Trying to convert a Arraylist of strings into one big comma separated string.

However when I use the

String joined = TextUtils.join(\", \", partici         


        
相关标签:
4条回答
  • 2021-01-15 12:30

    Try with kotlin

    val commaSeperatedString = listOfStringColumn.joinToString { it -> 
     "\'${it.nameOfStringVariable}\'" }
    

    // output: 'One', 'Two', 'Three', 'Four', 'Five'

    0 讨论(0)
  • 2021-01-15 12:34

    I'm trying to reproduce your error and am unable to. Here is my code:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_temp);
    
        List<String> list = new ArrayList<>();
        list.add("Philip Johnson");
        list.add("Paul Smith");
        list.add("Raja P");
        list.add("Ezhu Malai");
    
        String s = TextUtils.join(", ", list);
    
        Log.d(LOGTAG, s);
    }
    

    My output is Philip Johnson, Paul Smith, Raja P, Ezhu Malai as expected.

    Are you importing the correct TextUtils class?

    android.text.TextUtils;

    Given the new information, here is my approach:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_temp);
    
        callApi(type, new OnResponseListener<List<String>>() {
            @Override public void onResponse(List<String> list) {
                getSupportActionBar().setTitle(TextUtils.join(", ", list));
            }
        });
    }
    

    I don't know what networking library you're using, but you may have to define OnResponseListener as an interface. It's very easy:

    public interface OnResponseListener<T> {
        public void onResponse(T response);
    }
    

    You will then need to modify your callApi function to take an instance of OnResponseListener> and call it's onResponse method after completing the call.

    I would recommend looking into the Volley library, and reading the Android documentation about simple network calls.

    0 讨论(0)
  • 2021-01-15 12:40

    I use StringUtils.join from Apache Common Utilities.

    The code is super-simple just the way you wanted,

    StringUtils.join(participants,", ");
    

    Works flawlessly for me.

    EDIT

    As requested, here is the StringUtils.java file for those who just want to use this single utility class and not the entire library.

    0 讨论(0)
  • 2021-01-15 12:54

    I don't know what TextUtils does. This will do it.

    StringBuffer sb = new StringBuffer();
    for (String x : participants) {
        sb.append(x);
        sb.append(", ");
    }
    return sb.toString();
    

    Easy enough, just use that.

    0 讨论(0)
提交回复
热议问题