logo image

How to concatenate strings in Java forEach loop



From Java8 variables need to be effectively final for using them in closures. Following code shows how to concatenate a string from List of Strings while using Java forEach loop

import java.util.List;
import java.util.ArrayList;

public class StringConcatenation {
    public static void main(String[] args) {
        
        List<String> someList = new ArrayList<String>();
        someList.add("a");
        someList.add("b");
        someList.add("c");
        
        final StringBuilder builder = new StringBuilder();
        
        someList.forEach((val)->{
            builder.append(val + ",");
        });
        
        String concatenatedString = builder.toString();

        System.out.println(concatenatedString.substring(0, concatenatedString.length() - 1));
        
    }
}