Search code examples
javaandroidstringstringbuilder

Get String in a single or double line from ArrayList using string Buffer


I have an ArrayList that contains some elements and I am using String Buffer to get in a string. But When I am print the String I am getting in unorganized line. I want to get in single or double line.

  ArrayList<String> mCombinedList; // it contains some value I have already instantiate it  
    StringBuilder builder = new StringBuilder();
    for (String singleLine : mCombinedList) {
        if (builder.length() > 0) {
            builder.append(" ");
        }
        builder.append(singleLine);

        }
    String string = builder.toString();
    Log.e(TAG, "string builder "  +string );

After Implementing this code I am getting this result in Log.

abdul jani
                                                                         456
                                                                            Friend   User 3
                                                                          721015***
                                                                            Friend

**ArrayList value of mCombinedList; **

 [  abdul jani
                                                                            456
                                                                              Friend,   User 3
                                                                            721015***
                                                                              Friend]

Solution

  • During the final phase of your String build using StringBuilder, when you have collected all the strings, just call this regex to remove all the white spaces that are more than 2 which will clean up all the additional white spaces that got introduced due to empty strings in your source arraylist

    String string = builder.toString().replaceAll("\\s{2,}", " ").trim();