In this short post, we’d explain how to convert/ reduce a List of Strings into a single comma (,) separated String using Java-8 Streams API.
here’s the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.util.Arrays; import java.util.List; public class ListToString { public static String getCommaSeparatedString(List<string> input) { return input.stream() .reduce( // identity function for String concatenation "", (s1, s2) -> { System.out.println(s1 + " : " + s2); if ("".equals(s1)) { return s2; } else { return s1 + "," + s2; } }); } public static void main(String[] args) { // List<string> input = Arrays.asList("MySQL", "Oracle", "DB2"); System.out.println(getCommaSeparatedString(input)); } } </string></string> |