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

后端 未结 10 1239
你的背包
你的背包 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:25

    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 alos you you own delimiter to separate printing elements.

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

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

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

    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

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

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

    String list = Arrays.toString(customers.toArray()).replace("[", "").replace("]", "");
    
    0 讨论(0)
  • 2020-12-17 11:36

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