0

I have an ArrayList<String> that is added to periodically. What I want to do is to cast the entire ArrayList to a String without doing a loop. Can anybody tell me is it possible without using loop?

Edited: So we found some solutions, Like

list.stream().collect(Collectors.joining());

Or

String result = String.join(",", list);

or some others as well. Now Just for getting knowledge I put a question which one is the most optimal way for compiler?

Asad Ali Choudhry
  • 4,985
  • 4
  • 31
  • 36

3 Answers3

5

You could make a stream out of your list and collect it using joining collector :

list.stream().collect(Collectors.joining());

You can pass the separator to Collectors::joining method for example :

list.stream().collect(Collectors.joining("-"));

Or you can use String::join method :

String result = String.join(",", list);

where , is the separator.

Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
2

Given some ArrayList<String> s, all you need to use to get a String representation is s.toString().

The format is the following

[element1, element2, element3]
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
Ben I.
  • 1,065
  • 1
  • 13
  • 29
  • To expand: what you get from ArrayList.toStirng is a comma-separated list of elements, enclosed in brackets. (Of course, there probably is a loop involved, just not one that you have to write) –  Jun 03 '19 at 20:47
2

I Believe you can do

String.join(", ", list);

Hope this helps :)

Damian
  • 934
  • 8
  • 12