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?

6
  • 2
    Why don't you want a loop? Commented Jun 3, 2019 at 20:37
  • Just trying to get best optimal solution Commented Jun 3, 2019 at 20:37
  • arrayList.stream().collect(Collectors.joining(", ")) is one of the options. Commented Jun 3, 2019 at 20:38
  • 1
    "Best optimal solution" - You will not find a faster solution, all solutions somehow need to iterate through all items once. You can stream it for adding multi-threading to it. But the list needs to be huge for that to pay off. Commented Jun 3, 2019 at 20:45
  • 1
    You could always use Apache commons library, where it’s just ‘StringUtils.join(list, ", ")’ Commented Jun 3, 2019 at 20:46

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

I Believe you can do

String.join(", ", list);

Hope this helps :)

Comments

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]

1 Comment

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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.