Output ArrayList to String without [,] (brackets) appearing

后端 未结 10 1238
你的背包
你的背包 2020-12-17 10:30

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

List customers = new ArrayList<>();
L         


        
相关标签:
10条回答
  • 2020-12-17 11:11

    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);
    
    0 讨论(0)
  • 2020-12-17 11:13

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

    0 讨论(0)
  • 2020-12-17 11:14

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

    customers.toString().replace("[", "").replace("]", "")
    
    0 讨论(0)
  • 2020-12-17 11:15

    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.

    0 讨论(0)
  • 2020-12-17 11:18

    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.

    0 讨论(0)
  • 2020-12-17 11:25

    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()
    
    0 讨论(0)
提交回复
热议问题