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.
See Question&Answers more detail:
os