- Best way to convert an ArrayList to a string
- 27 Answers 27
- How can convert ArrayList<Long> to String in Java (Android)? [duplicate]
- How can convert ArrayList<Long> to String in Java (Android)? [duplicate]
- Convert Arraylist to Array, data of Arraylist is of custom class type
- How to convert a JSONObject to a String Array or ArrayList<String> in android
- Converting arraylist int to string
- 4 Answers 4
Best way to convert an ArrayList to a string
This question’s answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
I have an ArrayList that I want to output completely as a String. Essentially I want to output it in order using the toString of each element separated by tabs. Is there any fast way to do this? You could loop through it (or remove each element) and concatenate it to a String but I think this will be very slow.
or remove each element Be careful, removing elements from an ArrayList list is a big NO-NO, as your «loop» will take quadratic time due to shifting elements (provided that you loop from first to last element).
27 Answers 27
String listString = String.join(", ", list);
In case the list is not of type String, a joining collector can be used:
String listString = list.stream().map(Object::toString) .collect(Collectors.joining(", "));
this doesn’t work for what the OP said. String.join takes as second argument Iterable. So it works if you have a List that you want to display, but if you have List it will not call toString() in it as wanted by the OP?>
Why the hell this is not the first (and accepted) answer.. I always have to scroll down until I know it’s there.. elegant and concise
If you happen to be doing this on Android, there is a nice utility for this called TextUtils which has a .join(String delimiter, Iterable) method.
List list = new ArrayList(); list.add("Item 1"); list.add("Item 2"); String joined = TextUtils.join(", ", list);
Obviously not much use outside of Android, but figured I’d add it to this thread.
What about if my List contains custom Class? Like If I’ve List
Since TextUtils.join takes an Object[] , I’d assume that it’s calling toString() on each token. Does PatientDetails implement toString() ? If that doesn’t solve the problem, you may be stuck doing something with the Separator class.
public static String join(CharSequence delimiter, Iterable tokens) Using raw type in a new library is really a fail on Google’s side. Especially when it could have easily been generified to public static
org.apache.lang3.StringUtils does virtually the same, so your answer was absolutely of much use to me outside of Android 🙂
The popularity of this answer (currently the highest voted one) shows you that many java questions stem from Android development
Java 8 introduces a String.join(separator, list) method; see Vitalii Federenko’s answer.
Before Java 8, using a loop to iterate over the ArrayList was the only option:
DO NOT use this code, continue reading to the bottom of this answer to see why it is not desirable, and which code should be used instead:
ArrayList list = new ArrayList(); list.add("one"); list.add("two"); list.add("three"); String listString = ""; for (String s : list) < listString += s + "\t"; >System.out.println(listString);
In fact, a string concatenation is going to be just fine, as the javac compiler will optimize the string concatenation as a series of append operations on a StringBuilder anyway. Here’s a part of the disassembly of the bytecode from the for loop from the above program:
61: new #13; //class java/lang/StringBuilder 64: dup 65: invokespecial #14; //Method java/lang/StringBuilder."":()V 68: aload_2 69: invokevirtual #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 72: aload 4 74: invokevirtual #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 77: ldc #16; //String \t 79: invokevirtual #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 82: invokevirtual #17; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
As can be seen, the compiler optimizes that loop by using a StringBuilder , so performance shouldn’t be a big concern.
(OK, on second glance, the StringBuilder is being instantiated on each iteration of the loop, so it may not be the most efficient bytecode. Instantiating and using an explicit StringBuilder would probably yield better performance.)
In fact, I think that having any sort of output (be it to disk or to the screen) will be at least an order of a magnitude slower than having to worry about the performance of string concatenations.
Edit: As pointed out in the comments, the above compiler optimization is indeed creating a new instance of StringBuilder on each iteration. (Which I have noted previously.)
The most optimized technique to use will be the response by Paul Tomblin, as it only instantiates a single StringBuilder object outside of the for loop.
Rewriting to the above code to:
ArrayList list = new ArrayList(); list.add("one"); list.add("two"); list.add("three"); StringBuilder sb = new StringBuilder(); for (String s : list) < sb.append(s); sb.append("\t"); >System.out.println(sb.toString());
Will only instantiate the StringBuilder once outside of the loop, and only make the two calls to the append method inside the loop, as evidenced in this bytecode (which shows the instantiation of StringBuilder and the loop):
// Instantiation of the StringBuilder outside loop: 33: new #8; //class java/lang/StringBuilder 36: dup 37: invokespecial #9; //Method java/lang/StringBuilder."":()V 40: astore_2 // [snip a few lines for initializing the loop] // Loading the StringBuilder inside the loop, then append: 66: aload_2 67: aload 4 69: invokevirtual #14; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 72: pop 73: aload_2 74: ldc #15; //String \t 76: invokevirtual #14; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 79: pop
So, indeed the hand optimization should be better performing, as the inside of the for loop is shorter and there is no need to instantiate a StringBuilder on each iteration.
How can convert ArrayList<Long> to String in Java (Android)? [duplicate]
Now while copying data from ArrayList to Array I am getting error like class not found or while displaying on list view it is just showing some garbage value. Then I have sent that ArrayList to activity class where I need to display that data in ListView.
How can convert ArrayList<Long> to String in Java (Android)? [duplicate]
Possible Duplicate:
Best way to convert an ArrayList to a string
I need your help! I have array of JSon (esponse from Facebook). ArrayList. How can convert this array to String? Thanks.
StringBuilder sb=new StringBuilder(); for (Long l:list) sb.append(l);
Try using StringBuilder class
public String ConvertArrayToString(Long[] longArray) < if(longArray != null) < StringBuilder sb = new StringBuilder(longArray.length); for(int i = 0; i < longArray.length; i++) < sb.append(longArray[i]); >return sb.toString(); > return null; >
best way would be to iterate over ArrayList and build a String
ArrayList list = new ArrayList(); String listString = ""; for (long l : list)
UPDATE using StringBuilder is much better approach as Strings are immutable and everytime you append to String it creates new String in memory. also
«+» operator is overloaded for String and used to concatenated two String . Internally «+» operation is implemented using either StringBuffer or StringBuilder .
Android — ArrayList to Array of Strings in java, Depends on what you want to do. Both are correct. toArray() Returns an array containing all of the elements in this list in proper sequence (from first to last element). Refer here. toArray(T[] a) Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the …
Convert Arraylist to Array, data of Arraylist is of custom class type
I have retrieved data from database and added to Arraylist using a class called AddDetails. In AddDetails class I am assigning all values. Then I have sent that ArrayList to activity class where I need to display that data in ListView. Now while copying data from ArrayList to Array I am getting error like class not found or while displaying on list view it is just showing some garbage value.
private class SearchTask extends AsyncTask < @Override protected Void doInBackground(Void. arg0) < // TODO Auto-generated method stub DatabaseHandler db = new DatabaseHandler(); String Place = etSearch.getText().toString(); AddDetails details = new AddDetails(Place); alSearchResult = db.searchResultByPlace(details); arrStr = new String[alSearchResult.size()]; try < arrStr = (String[]) alSearchResult.toArray(); ArrayAdapteradapter = new ArrayAdapter(SearchActivity.this, android.R.layout.simple_list_item_multiple_choice, arrStr); lsSearchResult.setAdapter(adapter); > catch(Exception e) < Log.e("Error:" + e.toString()); >return null; > protected ArrayList searchResultByPlace(AddDetails details) < ArrayListalSearchData = null; try < String place = details.getPlace(); Cursor c = mDataBase.rawQuery("SELECT * FROM " + ESTATE_DETAILS + " WHERE " + strSearchType + " = " + "'" + place + "'", null); c.moveToFirst(); if(c.getCount() >0) < alSearchData = new ArrayList(); if (c.moveToFirst()) < do < details = new AddDetails(); details.setID(Integer.parseInt(c.getString(0))); details.setPlace(c.getString(1)); details.setArea(c.getString(2)); details.setType(c.getString(3)); details.setPhoneNumber(c.getString(4)); // Adding contact to list alSearchData.add(details); >while (c.moveToNext()); > > c.close(); > catch(SQLException e) < Log.e("Error:", e.toString()); >return alSearchData;
arrStr = (String[]) alSearchResult.toArray();
arrStr = alSearchResult.toArray(new String[0]);
Please do not access your listView lsSearchResult in background thread. Pass your result to onPostExecute().
Try to use following Code :
private class SearchTask extends AsyncTask> < @Override protected ArrayListdoInBackground(Void. arg0) < DatabaseHandler db = new DatabaseHandler(); String Place = etSearch.getText().toString(); AddDetails details = new AddDetails(Place); alSearchResult = db.searchResultByPlace(details); return alSearchResult; >protected void onPostExecute(ArrayList result) < ArrayAdapterarrayAdapter = new ArrayAdapter(SearchActivity.this,android.R.layout.simple_list_item_1, result); lsSearchResult.setAdapter(arrayAdapter); >
ArrayList stock_list = new ArrayList(); stock_list.add("stock1"); stock_list.add("stock2"); String[] stockArr = new String[stock_list.size()]; stockArr = stock_list.toArray(stockArr); for(String s : stockArr) System.out.println(s);
this is helpful for arraylist to array conversion also you can use arraylist directly with the arrayadapter no need to convert it to array
Convert ArrayList to String Array in Java, To convert the ArrayList to String Array by using the copyOf () method, we will access the ArrayList, convert it to objects from the ArrayList, and then convert it to String Array. Consider the below example to understand the implementation of this method: import java.util.*; public class ArrayListConversion2 < public static …
How to convert a JSONObject to a String Array or ArrayList<String> in android
I’m going to get the values of a JSONObject and put it in a String Array or ArrayList. the Problem is that I have a JSONObject not a JSONArray, and I can’t change the Webservice. This is my JSONObject:
ProgressBar progressbar = (ProgressBar) findViewById(R.id.progressbar); RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); progressbar.setVisibility(View.VISIBLE); StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener() < @Override public void onResponse(String response) < Toast.makeText(getApplicationContext(), "Response", Toast.LENGTH_SHORT).show(); progressbar.setVisibility(View.GONE); try < JSONArray array = new JSONArray(response); Toast.makeText(getApplicationContext(), "Try", Toast.LENGTH_LONG).show(); >catch (JSONException e) < e.printStackTrace(); Toast.makeText(getApplicationContext(), "Catch", Toast.LENGTH_LONG).show(); >> >, new Response.ErrorListener() < @Override public void onErrorResponse(VolleyError error) < Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show(); progressbar.setVisibility(View.GONE); >>); queue.add(stringRequest);
when I debug my code, it goes to CATCH. It doesn’t go to TRY, anyway!
I want something like this:
added changes to your code
ProgressBar progressbar = (ProgressBar) findViewById(R.id.progressbar); RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); ArrayList answersStringArray= new ArrayList(); // define string array progressbar.setVisibility(View.VISIBLE); StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener() < @Override public void onResponse(String response) < Toast.makeText(getApplicationContext(), "Response", Toast.LENGTH_SHORT).show(); progressbar.setVisibility(View.GONE); try < JJSONObject jsonObject = new JSONObject(response); //cast responce to jsonObject Iteratorkeys = jsonObject.keys(); // get the keys of the jsonObject while( keys.hasNext() )/iterrate over them String key = (String)keys.next(); answersStringArray.add(jsonObject.optString(key));> // add the string to our array of stings > catch (JSONException e) < e.printStackTrace(); Toast.makeText(getApplicationContext(), "Catch", Toast.LENGTH_LONG).show(); >> >, new Response.ErrorListener() < @Override public void onErrorResponse(VolleyError error) < Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show(); progressbar.setVisibility(View.GONE); >>); queue.add(stringRequest);
public static void main(String[] args) < //building your jsonObject(took only the 1st four ;P ) JSONObject objJsonObject = new JSONObject(); objJsonObject.put("THR", "تهران"); objJsonObject.put("MHD", "مشهد"); objJsonObject.put("KIH", "کیش"); objJsonObject.put("IFN", "اصفهان"); String [] strArray= new String[objJsonObject.length()]; int i = 0; //adding your required data into a array for (String key: objJsonObject.keySet()) < strArray[i] = objJsonObject.getString(key); i++; >//printing your data for (int j = 0; j < strArray.length; j++) < System.out.println(strArray[j]); >>
Android — Convert an ArrayList to, So, typecasting cannot help with conversion. The object should already be of that type for typecasting to work. If it is of a different type, you have to write code to convert it. public class ListProcessing < public static void main (String [] args) < List
Converting arraylist int to string
I am trying to convert an arraylist of integers to an string in reverse. eg (1,2,3,4) converts to «4321». However I am unable to get my code to work mainly due to the primitive data type error (basically why you give my an arraylist to do an array thing). My code is currently
public String toString() < int n = arrList.size(); if (n == 0) return "0"; for (int i = arrList.size(); i >0; i--); int nums= arrList[i]; char myChar = (char) (nums+ (int) '0'); String result = myChar.toString(arrList); return result; >
4 Answers 4
- Your loop had the wrong range and it didn’t do anything, since you terminated it with ; .
- In addition, arrList[i] is the way to access an element of an array. To access an element of an ArrayList you use arrList.get(i) .
- Finally, you should accumulate the characters / digits somewhere before converting them to a String. I suggest a StringBuilder.
StringBuilder sb = new StringBuilder(); for (int i = arrList.size() - 1; i >= 0; i--) < int num = arrList.get(i); sb.append(num); >String result = sb.toString();
You have many problems. First, you should remove ; after the for loop.
Second, you are not concatenating the result, just saving the last value.
Third, you should loop from the last index, which is arrList.size() — 1 .
Fourth, note that the element at place 0 should be counted as well, so you should change your condition to i >= 0 .
Finally, accessing arraylist’s elements should be done using the method get : arrList.get(i) .
Now after you understood what your problems are, I would like to suggest a better solution using Java 8:
Collections.reverse(arrList); String listString = arrList.stream().map(Object::toString) .collect(Collectors.joining(""));