I need to print all arraylist values at a time using concat.
Here is my code:
ArrayList lst = new ArrayList();
lst.add(\"hi\"
The error in your code is pretty small. In each iteration you assign a value to the result
variable. However instead of updating your existing content you just erase it and enter a new value.
You do result = element + " "
. But it should be something like result = result + element + " "
or the same in short:
result += element + " ";
This way the first iteration will save hi
in it and after that hello
gets appended resulting in hi hello
(instead of overriding the content of the first iteration).
Note that it now also has the whitespace at the end. You could delete it with result = result.substring(0, result.length() - 1)
. Or not add it in the last iteration, but then you need to count the iterations.
Please note that Java has a class StringJoiner that does exactly what you want, joining some elements together and also using a delimiter like whitespace. You use it like this:
StringJoiner sj = new StringJoiner(" ");
while(itr.hasNext()) {
Object element = itr.next();
sj.add(element);
}
String result = sj.toString();
Also note that since Java 8 there is an even shorter version of it:
String result = String.join(" ", list);
Please prefer the List
interface to the ArrayList
concrete type. Assuming you are using Java 8+, you might use a Stream
and Collectors.joining
(and Arrays.asList
) like
List<String> lst = Arrays.asList("hi", "hello");
String r = lst.stream().collect(Collectors.joining(" "));
System.out.println(r);
Which outputs
hi hello
As requested.