Saturday, February 23, 2019

Java ArrayList to single string without using loop




I have an ArrayList 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?


Answer



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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...