22

OK, so I have an ArrayList that I need to return as a String. Right now I am using this approach:

List<Customer> customers = new ArrayList<>();
List<Account> accounts = new ArrayList<>();


public String customerList() 
{
    String list = Arrays.toString(customers.toArray()); 
    return list;
}

public String accountList() 
{ 
    String account = Arrays.toString(accounts.toArray()); 
    return account;
}

This works fine, but the problem is that I get brackets around the text. I am getting stuff like:

 Customer list:
 --------------
 [Name: Last, First
 , Name: Last, First
 , Name: Last, First
 ]

When I want something like this:

 Customer list:
 --------------
 Name: Last, First
 Name: Last, First
 Name: Last, First

However, unlike similar questions, I don't simply want to output line by line. I need to store the ArrayList in a String without the brackets so I can work with it.

EDIT: It should be noted that the one comma in the version I want it to look like was placed there by a method in a different class:

public final String getName()  
    { 
        return getLast() + ", " + getFirst(); 
    }

EDIT 2: I was able to find a complete solution by adapting the two answers I was given. It was difficult deciding which was the "answer" because I found both useful, but went with the one that I could use more selectively.

public String customerList() 
{
    String list = Arrays.toString(customers.toArray()).replace(", N", "N").replace(", N", "N");
    return list.substring(1,list.length()-1);
}

To remove the brackets I used the modified return. Removing the comma required me to focus on the fact that each line will start with an "N", but the flaw in this approach is that the code would break if I forget to change it here if I change it there. Still, it solves my specific problem, and I can always notate to myself in both places as needed.

Elliander
  • 503
  • 1
  • 9
  • 19
  • Have a look at [Concantenating elements in an array to a string](http://stackoverflow.com/questions/14957964/concantenating-elements-in-an-array-to-a-string) – LinkBerest Sep 25 '15 at 02:58
  • I can't use String Builder for this. – Elliander Sep 25 '15 at 02:59
  • `String account = Arrays.toString(accounts.toArray()); return account.substring(1,account.length()-1);` – Rodrigo Gomes Sep 25 '15 at 03:00
  • @RodrigoGomes aha! That removes the brackets! I still see extra commas, but that might be from somewhere else so I'm double checking. Can you post that as an answer? – Elliander Sep 25 '15 at 03:04
  • Why you can't use `StringBuilder`? If you take a look inside `Arrays.toString` you'll see that it's implemented by appending elements to `StringBuilder`. I suggest you to copy code from there and remove lines that are responsible for appending commas and brackets. – Aivean Sep 25 '15 at 03:10
  • try: `account..replaceAll(" , ", "\r\n")` to remove those extras commas But I suggest you create a method to iterate over the array and create your return as you want. The solutions I gave I consider as workaround ;) – Rodrigo Gomes Sep 25 '15 at 03:12
  • I'm in college following a UML Diagram. If I use any programming feature not explicitly mentioned they will deduct points, but the teacher is not good about answering questions either forcing me to fill in my understanding elsewhere. Anyway, that's why I can't use StringBuilder. Last time I used that feature I got in trouble because it was too advanced for me or some such nonsense. Just last week I used ArrayList instead of modular arrays before we were ready (because it's better) and didn't get any credit. – Elliander Sep 25 '15 at 03:23

11 Answers11

45

You could try to replace the '[' and ']' with empty space

String list = Arrays.toString(customers.toArray()).replace("[", "").replace("]", "");
bmarkham
  • 1,590
  • 15
  • 27
  • That approach works as well :) The downside of course is if a bracket is ever wanted within the string, but might also be a good way to prevent characters like that from being used. – Elliander Sep 25 '15 at 03:05
  • You're right. This solution is only really catered to your specific solution,. – bmarkham Sep 25 '15 at 03:08
  • Right. I tried to adapt it to removing the extra commas instead since the other answer removed the brackets, but unfortunately doing so removed the commas I wanted as well. – Elliander Sep 25 '15 at 03:14
  • oh! I was able to adapt it anyway! – Elliander Sep 25 '15 at 03:17
  • java 8 : String listCustomers = list.stream().map(Object::toString).collect(Collectors.joining()); – user3072470 Mar 19 '20 at 22:53
9

I think the best solution to print list without brackets and without any separator( for java 8 and higher )

String.join("", YOUR_LIST);

You can also add your own delimiter to separate printing elements.

String.join(", \n", YOUR_LIST);

example above separate each list element with comma and new line.

Dave Kraczo
  • 748
  • 9
  • 9
6

Java 8 version

List<Integer> intList = new ArrayList<Integer>();
intList.add(1);
intList.add(2);
intList.add(4);
System.out.println(intList.stream().map(i -> i.toString()).collect(Collectors.joining(",")));

Output: 1,2,4

yejianfengblue
  • 2,089
  • 1
  • 14
  • 18
4

Can directly convert list/set to string and perform action on it

customers.toString().replace("[", "").replace("]", "")
3

A possible solutions is:

String account = Arrays.toString(accounts.toArray()); 
return account.substring(1,account.length()-1);

Or do you override the toString method to return the string as per you wanted.

Rodrigo Gomes
  • 346
  • 1
  • 5
3

You can use the method substring() to remove starting and ending brackets without tampering any entries in the ArrayList. I used something like this to convert a ArrayList<String> to String

String str = list.toString().substring(1, list.toString().length() - 1);
Dheeraj vats
  • 348
  • 5
  • 17
2

If you want your output to look like: item1, item2, item3

Arrays.toString(customers.toArray()).replace('[', ' ').replace(']', ' ').trim()

If you want your output to look like: item1 item2 item3

Arrays.toString(customers.toArray()).replace('[', ' ').replace(']', ' ').replace(',', ' ').trim()
Thev
  • 51
  • 4
0

You can override the toString() method and represent the output in whatever format you

0

You can try this.

String listAsStr = myList.toString(); // get list as string
listAsStr = listAsStr.substring(1,listAsStr.length()-1); // removing first and last bracket

This will return the string without first and last brackets.

Rajat
  • 1
  • 2
0

One more one-line solution for printing:

System.out.println(result.toString().replaceAll("[\\]\\[\\,]", ""));
Meow Meow
  • 637
  • 6
  • 17
-3

Anyone still stuck on this, try using a for-each loop.

ArrayList<String> list = new ArrayList<>(); // default size of 10

/*add elements to 
the ArrayList*/

for(String element: list)
System.out.println(element);
Premlatha
  • 1,676
  • 2
  • 20
  • 40
  • Did you read the problem described in the question? If not please read it fully before attempting to provide a solution. – Thangadurai Jan 30 '20 at 02:19