By Alvin Alexander. Last updated: August 29, 2017
Android FAQ: How do I convert a list of strings (or a list of objects) to a single, combined string?
In Android, if you want to convert a list of strings to a String
, I just saw this approach:
List<String> list = new ArrayList<String>(); list.add("foo"); list.add("bar"); list.add("baz"); String joined = TextUtils.join(", ", list);
That approach works great if you happen to have a List<String>
, but if you want to convert a list of objects to a String
, I think you’ll have to use the old-fashioned approach:
StringBuilder sb = new StringBuilder(); int count = 1; for (User u: users) { sb.append("" + count++ + ": " + u.firstName + " " + u.lastName + "\n"); } mEditText.setText(sb.toString());
As shown, I use that approach to convert a list of users to a list of custom strings.
There may be other ways to approach this as Android adopts Java 8 standards, but for now, these examples show the best ways I know to convert a list of strings and a list of custom objects to a single string.