To concatenate strings in a list in Java, you can use a loop to iterate over the list and append each string to a StringBuilder.
In this example,
words
with some strings.StringBuilder
named result
to store the concatenated string.result
with a specified separator.import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>();
words.add("Hello");
words.add("World");
words.add("!");
StringBuilder result = new StringBuilder();
for (String word : words) {
result.append(word).append(" ");
}
System.out.println("Concatenated string: " + result.toString().trim());
}
}
Concatenated string: Hello World !
In this example,
phrases
with different strings.import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<String> phrases = new ArrayList<>();
phrases.add("Good");
phrases.add("morning");
phrases.add("everyone");
StringBuilder result = new StringBuilder();
for (String phrase : phrases) {
result.append(phrase).append(", ");
}
System.out.println("Concatenated string: " + result.toString().trim());
}
}
Concatenated string: Good, morning, everyone,
In this tutorial, we learned How to Concatenate Strings in List in Java language with well detailed examples.